How to specify id when uses include in layout xml file

Viewed 89570

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 ?

12 Answers

If you have set id to either root tag of included layout then you can use that id or you can set id to included layout.

But you can not set id to both it may throw exception.

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

....
</LinearLayout>

Or

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        android:id="@+id/llBottomMainView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

....
</LinearLayout>

To specify the id when you are including a xml file is like setting it to any xml element

Example:

*list_layout.xml*
`<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvNames"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>`


*activity_main.xml*
`<RelativeLayout
      tools:context=".MainActivity">

      <include
          layout="@layout/list_layout"
          android:id="@+id/myList" />
</RelativeLayout>`

Now if you want to get that to use in .kt file, just use normally findViewById

Exemplo

*MainActivity.kt*

`val myList: RecycleView = findViewById(R.id.myList)`

Wow, I can't believe this question doesn't have the right answer yet. It's simple tags suck. You can only change things that start with android:layout_ which android:id doesn't match. So the answer is you can't. Sorry. What you can do instead is create a class that will be a ViewGroup which will inflate the included views inside, then add that as a tag in your layout, but that's about it.

Related