The <include> tag lets you to divide your layout into multiple files: it helps dealing with complex or overlong user interface.
Specifically, Android considers XML-based layouts to be resources, and as such, layout files are stored in the reslayout directory inside your Android project. Each XML file contains a tree of elements specifying a layout of widgets and containers that make up one View.
To efficiently re-use complete layouts, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Reusing layouts is particularly powerful as it allows you to create reusable complex layouts.
What Activity method you use to retrieve a reference to an Android view by using the id attribute of a resource XML? The findViewById(int id) method looks for a child view with the given id.
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.
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.
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" />
I think the top answer misses the most important point and might mislead people into thinking the <include/>
tag creates a View that holds the include contents.
The key point is that include's id is passed to the root view of the include's layout file.
Meaning that this:
// activity_main.xml
<include layout="@layout/somelayout" android:id="@+id/someid"/>
// somelayout.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Becomes this:
// activity_main.xml
<ImageView
android:id="@+id/someid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With