原文地址:http://android.xsoftlab.net/training/improving-layouts/reusing-layouts.html
尽管Android提供了种类繁多的常用控件,但是有时你可能希望重用一些比较复杂的布局。如果要重用这些布局,可以使用< include/>标签与< merge/>标签,它们可将一个布局嵌入进另一个布局中。
可重用布局这项功能特别强大,它可以使你创建那些复杂的可重用布局。比方说,可以用来创建一个含有yes和no按钮的容器或者一个含有progressBar及一个文本框的容器。它还意味着程序可以对这些布局进行单独控制。所以,虽然说你可以通过自定义View的方式来实现更为复杂的UI组件,但是重用布局的方法更简便一些。
创建一个可重用的布局
如果你已经知道哪一个布局需要重用,那么就创建一个新的xml文件用来定义这个布局。下面就定义了一个ActionBar的布局文件,众所周知,ActionBar是会在每个Activity中统一出现的:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width=”match_parent”android:layout_height="wrap_content"android:background="@color/titlebar_bg"><ImageView android:layout_width="wrap_content"android:layout_height="wrap_content" android:src="@drawable/gafricalogo" />
</FrameLayout>
使用< include/>标签
在希望添加重用布局的布局内,添加< include/>标签。下面的例子就是将上面的布局加入到了当前的布局中:
<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>
你也可以重写布局的参数,但只仅限于以android:layout_*开头的布局参数。就像下面这样:
<include android:id=”@+id/news_title”android:layout_width=”match_parent”android:layout_height=”match_parent”layout=”@layout/title”/>
如果你要重写< include>标签指定布局的布局属性,那么必须重写android:layout_height及android:layout_width这两个属性,以便使其它属性的作用生效。
使用< merge>标签
在将一个布局内嵌进另一个布局时,< merge>标签可以帮助消除冗余的View容器。举个例子,如果你的主布局是一个垂直的LinearLayout,在它的内部含有两个View,并且这两个View需要在多个布局中重用,那么重用这两个View的布局需要有一个root View。然而,使用单独的LinearLayout作为这个root View会导致在一个垂直的LinearLayout中又嵌了一个垂直的LinearLayout。其实这个内嵌的LinearLayout并不是我们真正想要的,此外它还会降低UI性能。
为了避免出现这种冗杂的View容器,你可以使用< merge>标签作为这两个View的root View:
<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>
那么现在再使用这个布局的时候,系统会自动忽略< merge>标签,并会将两个Button View直接加入到布局< include/>标签所指定的位置。