Categories
android android-layout include merge

Can some clarify usage of and

I just need someone to tell me if I understood correctly when to use <include> and when <merge>.

So, I make a header layout which I want to include into some other XML layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header text" />
</LinearLayout>

And I include it into some other XML this way (which is pretty basic):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<include
android:id="@+id/header"
layout="@layout/top"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>

This will work well, no issue about it. But in order to optimize the code, I have to use <merge> in the layout which gets included. So the top layout should not have a tag <LinearLayout> but it must look like this:

<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header text" />
</merge>

Have I understood this correctly?

Yes you understood it correctly. merge is used as pseudo parent element to reduce the number of levels in view trees.
Just check this link, it gives very good explanation of merge.

In your header file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<include
android:id="@+id/header"
layout="@layout/top"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>

<LinearLayout> doesn’t make any difference when your file is included in other file you mentioned. So it’s a good thing to use merge instead.

Since in XML you must use a single parent element and the rest of the XML elements should be included in it, you should use merge as single parent element and can avoid adding unnecessary parent layout.

Just avoid ‘merge’ when you want to apply a layout differently than layout is defined in file in which your content is inclded.