Android 如何从膨胀布局中获取视图的引用

Android 如何从膨胀布局中获取视图的引用,android,android-tablelayout,layout-inflater,Android,Android Tablelayout,Layout Inflater,我使用setContentView()设置了一个巨大的活动布局。在该布局中,我有一个要填充的TableLayout(在活动中名为TableLayout)。该TableLayout的行是布局文件中的自定义视图(我们将该文件称为tablerow\u layout.xml)。在这个布局中,我有一些TextView和ImageView。我想做的是在创建行时以编程方式更改TextView的内容。这是我的代码: LayoutInflater layoutInflater = (LayoutInflater)

我使用
setContentView()
设置了一个巨大的活动布局。在该布局中,我有一个要填充的
TableLayout
(在活动中名为
TableLayout
)。该TableLayout的行是布局文件中的自定义视图(我们将该文件称为
tablerow\u layout.xml
)。在这个布局中,我有一些TextView和ImageView。我想做的是在创建行时以编程方式更改TextView的内容。这是我的代码:

LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newRow = layoutInflater.inflate(R.layout.tablerow_layout, null, false);
TextView name = (TextView) newRow. findViewById(R.id.tablerow_name);
name.setText("THIS LINE");
tableLayout.addView(newRow);
不幸的是,当我试图更改TextView的内容时,我的应用程序崩溃了。我知道我可以使用ListView来实现这一点,但是我通常只有少量的行,并且为ListView创建另一个适配器的开销非常大

正如@ρцσѕρєєK建议的那样,我也尝试了newRow.findviewbyd(…)而不是findviewbyd(…),没有任何区别

如何从膨胀布局中获取视图的引用

使用从
LayoutInflater.inflate
方法返回的
View
对象访问布局中的视图,该布局作为第一个参数传递给
inflate
方法

在您的情况下,使用
newRow
对象从
R.layout.tablerow\u layout
layout访问视图:

TextView name = (TextView)newRow.findViewById(R.id.tablerow_name); 

您缺少在文本视图中设置
newRow

  View newRow = layoutInflater.inflate(R.layout.tablerow_layout, null, false);
  TextView name = (TextView)newRow.findViewById(R.id.tablerow_name);

使用IntelliJ Amiya和ρ∑ѕρєK的答案,这段代码对我有效

LayoutInflater inflater = LayoutInflater.from(this);
    LinearLayout linearLayout = 
(LinearLayout)findViewById(R.id.profileView);
    ViewGroup viewGroup = linearLayout;

    for (int i = 0; i < NUM_OF_PROFILES; i++){

        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.profile_badge_layout, viewGroup, false);
        linearLayout.addView(layout);

        TextView names = (TextView)layout.findViewById(R.id.profileName);
        ImageView images = (ImageView)layout.findViewById(R.id.profileImage);

        names.setText(""+i);


        viewGroup = layout;
    }
LayoutInflater充气机=LayoutInflater.from(此);
线性布局线性布局=
(线性布局)findViewById(R.id.profileView);
ViewGroup ViewGroup=线性布局;
对于(int i=0;i

每个文本都有自己的i值。我认为您需要先添加视图。然后您可以更改值

以前尝试过此操作,但没有任何区别。要编辑我的问题它只是要阻止我的应用程序崩溃,而不设置实际文本。
LayoutInflater inflater = LayoutInflater.from(this);
    LinearLayout linearLayout = 
(LinearLayout)findViewById(R.id.profileView);
    ViewGroup viewGroup = linearLayout;

    for (int i = 0; i < NUM_OF_PROFILES; i++){

        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.profile_badge_layout, viewGroup, false);
        linearLayout.addView(layout);

        TextView names = (TextView)layout.findViewById(R.id.profileName);
        ImageView images = (ImageView)layout.findViewById(R.id.profileImage);

        names.setText(""+i);


        viewGroup = layout;
    }