gpt4 book ai didi

android - 如何从膨胀的布局中获取 View 的引用

转载 作者:太空宇宙 更新时间:2023-11-03 11:56:03 25 4
gpt4 key购买 nike

我使用 setContentView() 为我的 Activity 设置了一个巨大的布局。在该布局中,我有一个要填充的 TableLayout(在我的 Activity 中名为 tableLayout)。该 TableLayout 的行是布局文件中的自定义 View (我们称该文件为 tablerow_layout.xml)。在这个布局中,我有一些 TextViews 和 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.findViewById(...) 而不是 findViewById(...) 没有任何区别

最佳答案

您缺少在 Textview 中设置 newRow

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

关于android - 如何从膨胀的布局中获取 View 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32374809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com