在我的Android项目中,我有一个类似的xml(item.xml):
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />
和另一个类似的xml(layout.xml):
<include layout="@layout/item"/>
<include layout="@layout/item"/>
<include layout="@layout/item"/>
<include layout="@layout/item"/>
<include layout="@layout/item"/>
在我的Java文件中,我放了一个setText,就像这样:
((TextView)findViewById(R.id.textView)).setText("hello");
结果,我只有第一个textView,其中包含我设置的文本("hello")。其他为空白。
我想在所有的include上加上相同的文本。
为什么这不起作用?
通过下面的代码非常容易做到。对于相同的示例,它看起来如下:
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.layout,
null);
for (int i = 0; i < 5; i++) {
View custom = inflater.inflate(R.layout.item, null);
TextView tv = (TextView) custom.findViewById(R.id.text);
tv.setText("hello");
parent.addView(custom);
}
setContentView(parent);