Layout xml merge tag

If you have a section of layout that you wish to reuse, it can be added using the <include> tag. Typically the code you are including would need a root view e.g. LinearLayout. However, if that root view would result in redundant code e.g. a vertical LinearLayout before the <include> tag immediately followed by the LinearLayout inside the reusable code, then instead of providing a root view for your reusable code then use the <merge> tag.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

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

    <TextView android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />

    ...

</LinearLayout>

 

 

// This is the block of reusable code
<merge xmlns:android="http://schemas.android.com/apk/res/android"> // No need for a root view here if it is to be nested inside a ViewGroup anyway. Putting a vertical LinearLayout here would produce a redundant ViewGroup

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/add"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/delete"/>

</merge>