How to specify id when uses include in layout xml file

In my layout xml file, I have included other layout xml file (each with a different android id).

<include layout="@layout/view_contact_name" android:id="+id/test1"/>
<include layout="@layout/view_contact_name" android:id="+id/test2"/>

But when I run it in the emulator, and start Hierarchy Viewer, each of the layout still shows 'NO_ID', and in my code, I have findViewById(R.id.test1) and findViewById(R.id.test2) both returns null.

Can anyone please help me with my problem ?


Solution 1:

Specify the ID in the <include>

<include layout="@layout/test" android:id="@+id/test1" />

Then use two findViewById to access fields in the layout

View test1View = findViewById(R.id.test1);
TextView test1TextView = (TextView) test1View.findViewById(R.id.text);

Using that approach, you can access any field in any include you have.

Solution 2:

I found out, that if you are using <merge> tag in your include layout, then the ID of include transfers to the merge tag which is not real view.

So either remove merge, or replace it with some layout.

Tor Norbye wrote:

The <include> tag is not a real view, so findByView will not find it. The @id attribute (and any other attributes you've set on the include tag) gets applied on the root tag of the included layout instead. So your activity.getView(R.id.included1) should in fact be the <TextView> itself.