Re-Using Layouts With Include
Re-Using Layouts With Include
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/titlebar_bg"
tools:showIn="@layout/activity_main" >
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/gafricalogo" />
</FrameLayout>
The root View should be exactly how you'd like it to appear in each layout to which
you add this layout.
Note: The tools:showIn attribute in the XML above is a special attribute that is removed during
compilation and used only at design time in Android Studio—it specifies a layout
that includes this file, so you can preview (and edit) this file as it appears while embedded in a
parent layout.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/app_bg"
android:gravity="center_horizontal">
<include layout="@layout/titlebar"/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />
...
</LinearLayout>
You can also override all the layout parameters (any android:layout_* attributes)
of the included layout's root view by specifying them in the <include/> tag. For
example:
<include android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/title"/>
However, if you want to override layout attributes using the <include> tag, you must
override both android:layout_height and android:layout_width in order for
other layout attributes to take effect.
To avoid including such a redundant view group, you can instead use
the <merge> element as the root view for the re-usable layout. For example:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<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>
Now, when you include this layout in another layout (using the <include/> tag), the
system ignores the <merge> element and places the two buttons directly in the
layout, in place of the <include/> tag.