How to Embed one XML Layout in Another in Android

It’s a common requirement when we have to make one layout and need to use it on multiple screens. Using include tag we can embed one XML layout in another in Android. In the following example its shown how you can include one layout in another.

Include XML Layout

<include
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    layout="@layout/layout_to_include"
    />

Example to Embed one XML Layout in Another in Android

Let’s assume you have 2 XML layouts and your want to include layout1 into layout2.

layout1 code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Hey! I am going to embed in another layout"/>

</RelativeLayout>

layout2 code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/tv_heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="18sp"
        android:textStyle="bold"
        android:text="Following is the included layout"/>

    <include
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/layout1"
        android:layout_below="@+id/tv_heading"
        />

</RelativeLayout>
Include XML Layout in Android

That’s it. Enjoy 🙂

For other helping, code snippets have a look at our Articles List.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: