How to use the include other Layout of Android?

5

Hello, I would like to know how to use the Include Other Layout and what it is for.

    
asked by anonymous 05.04.2015 / 03:56

1 answer

9

If you are referring to tag <include /> , it is to include a "subtree" in the place where it is declared. It is often used when you have a layout that can be reused in other layouts or declared alone for a better organization.

It has the layout attribute, where you set the reference for the layout you want to include.

An example would be:

layout_principal.xml

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

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

</LinearLayout>

layout_secondary.xml

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

    <!-- Conteudo do layout_secundario -->

</FrameLayout>

The final result when the layout is inflated will be:

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

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

        <!-- Conteudo do layout_secundario -->

    </FrameLayout>

</LinearLayout>

Remembering that just like any other layout , layout_secundario needs to have only one root element. To include more than one element, you must have a ViewGroup (excluding ScrollView that can only have one child).

Another widely used tag is <merge /> , which excludes the need to have only one root element. With this tag, you can declare exactly how layout will be included.

For example:

Assuming the same layout_principal , the layout_secundario with the use of the <merge /> tag would be:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Conteudo do layout_secundario -->

</merge>

The final result, when layout_principal is inflated, will be:

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

    <!-- Conteudo do layout_secundario -->

</LinearLayout>

The end result is best in terms of the amount of View's (the less Views , the better). But you need to have control over the layout that uses the <merge /> tag, because if used improperly it can cause unexpected results.

    
05.04.2015 / 04:58