In my layout xml file, I have included other layout xml file (each with a different android id).
Problem is we try to use id which is not declared in current layout file.
Instead of declaring again, id can be simply referred using @+id/
. If you refactor original id name through Android Studio it does refactor in included layout as well.
<include layout="@layout/toolbar"/>
<TextView
android:id="@+id/txt_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
**android:layout_below="@+id/toolbar"**
android:layout_marginTop="16dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"/>
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.
When talking about include you either have an id on the root view inside the included layout file or on the include line itself and not on both. For example:
<include layout="@layout/layout1" android:id="@+id/layout1"/>
<RelativeLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout2">
</RelativeLayout>
The above example is wrong because technically you have two id's declared for the same layout. So what you have to do is pick which element will have the id.
Romain Guy indicates that you can override the ID of an included layout by putting an android:id
attribute inside the <include>
tag.
<include android:id="@+id/cell1" layout="@layout/workspace_screen" />
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.
yes is like this, but careful when the layout inserted in include field is a custom one and you want to access that root layout. That layout in this case @layout/test test, is actually returned in first line.
test test1View = (test)findViewById(R.id.test1);