尽管Android提供了各种各样的控件来支持控件级的重用,但是您可能有特别的布局需要重用。您可以通过 <include/> 标签来重用整个布局;使用 <merge/> 标签在当前布局中引入其他布局。
布局重用功能让您可以重用复杂的布局,该功能是非常好用的。例如,一个 带有 确定、取消 两个按钮的布局;或者带有描述文字的自定义进度条。这就意味着,在您的程序中那些出现在各个布局文件中的一样的代码可以单独的提取出来,放到一个独立的布局文件中,然后其他的布局引用这个文件即可。 可Java中的函数重构一样,把相同的代码重构为一个函数,其他代码调用这个函数即可。通过继承 View 可以创建自定义控件,而通过重用布局文件更加简化了这个过程。
创建可重用的布局
如果您已经设计好了需要重用的布局,只有创建一个布局XML文件即可。例如,这里是一个来自于 G-Kenya codelab 的布局文件,定义了在每个Activity中都要使用的一个自定义标题 (titlebar.xml):
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width=”match_parent” android:layout_height="wrap_content" android:background="@color/titlebar_bg"> <ImageViewandroid:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gafricalogo"/> </FrameLayout>
布局中的根 View 应该就是您希望添加到目标布局中的控件。
使用 <include> 标签
在您希望添加可重用布局的文件中,使用 <include/> 标签引入重用的布局。例如,这里是 G-Kenya codelab 中引用上面定义的标题布局的代码:
<LinearLayoutxmlns: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"> <strong><includelayout="@layout/titlebar"/></strong> <TextViewandroid:layout_width=”match_parent” android:layout_height="wrap_content" android:text="@string/hello" android:padding="10dp"/> ... </LinearLayout>
您还可以在 <include/>标签里面重新定义布局参数 (所有 android:layout_* 参数) ,例如:
<includeandroid:id=”@+id/news_title” android:layout_width=”match_parent” android:layout_height=”match_parent” layout=”@layout/title”/>
使用 <merge> 标签
<merge /> 标签帮助你消除不必要的View group。 例如 ,如果您的主布局是一个垂直方向的LinearLayout,而里面引用了另外一个可重用的布局,该布局同样是垂直方向的 LinearLayout 为根布局,这样的话最终的布局里面会有两个垂直方向的 LinearLayout, 而引用的那个LinearLayout 是多余的。
为了避免这种多余的View Group出现,您可以使用 <merge> 标签做为可重用布局的根标签。 如下所示:
<mergexmlns: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>
这样,当你在其他的布局中引用这个布局的时候(使用 <include/> 标签),系统将会忽略 <merge> 标签,然后把那两个按钮直接放到 <include/> 标签的位置。