setText on the same id (with various include)

时间:2015-10-29 15:41:24

标签: android

In my Android project, I have one xml (item.xml) like this :

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView" />

and one other xml (layout.xml) like this :

<include layout="@layout/item"/>
<include layout="@layout/item"/>
<include layout="@layout/item"/>
<include layout="@layout/item"/>
<include layout="@layout/item"/>

in my Java file, I put a setText, like that :

((TextView)findViewById(R.id.textView)).setText("hello");

In the result, I have only the first textView with the text I have set ("hello"). The other are blank.

I would like to put the same text on all the include.

Why this is not working ?

1 个答案:

答案 0 :(得分:2)

通过以下代码很容易做到。对于同样的例子,它看起来如下:

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);