How to use include other Android Layout?

Asked

Viewed 3,466 times

7

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

1 answer

12


If you’re referring to tag <include />, it serves to include a "sub-tree" in the place where it is declared. In general it is widely used when you own a layout that can be reused in other layouts or declared in isolation for better organisation.

She has the attribute layout, where you set the reference to 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_secundario.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, the layout_secundario need to have only one root element. To include more than one element, you need to have one ViewGroup (excluding the ScrollView who can only have one child).


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

For example:

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

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

    <!-- Conteudo do layout_secundario -->

</merge>

The final result, when the layout_principal will be inflated:

<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 turns out to be better in terms of quantity of View's (how much less Views, better). But you need to have a control on the inclusion of layout who uses the tag <merge />, because if used without due attention can cause unexpected results.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.