How to include layout inside layout?
Edit: As in a comment rightly requested here some more information. Use the include
tag
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/yourlayout" />
to include the layout you want to reuse.
Check this link out...
Note that if you include android:id...
into the <include />
tag, it will override whatever id was defined inside the included layout. For example:
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/some_id_if_needed"
layout="@layout/yourlayout" />
yourlayout.xml:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/some_other_id">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button1" />
</LinearLayout>
Then you would reference this included layout in code as follows:
View includedLayout = findViewById(R.id.some_id_if_needed);
Button insideTheIncludedLayout = (Button)includedLayout.findViewById(R.id.button1);
Use <include />
tag.
<include
android:id="@+id/some_id_if_needed"
layout="@layout/some_layout"/>
Also, read Creating Reusable UI Components and Merging Layouts articles.
Try this
<include
android:id="@+id/OnlineOffline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
layout="@layout/YourLayoutName" />
From Official documents about Re-using Layouts
Although Android offers a variety of widgets to provide small and re-usable interactive elements, you might also need to re-use larger components that require a special layout. To efficiently re-use complete layouts, you can use the tag to embed another layout inside the current layout.
Here is my header.xml file which i can reuse using include tag
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="@string/app_name"
android:textColor="#000000" />
</RelativeLayout>
No I use the tag in XML to add another layout from another XML file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f0f0f0" >
<include
android:id="@+id/header_VIEW"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="@layout/header" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#ffffff"
android:orientation="vertical"
android:padding="5dp" >
</LinearLayout>