翻自:http://developer.android.com/training/improving-layouts/reusing-layouts.html 尽管Android提供了各种组件来实现小而可复用的交互元素,你也可能因为布局需要复用一个大组件。为了高效复用完整布局,你可以使用
创建可复用布局
如果你已经知道哪个布局需要重用,就创建一个新的xml文件来定义布局。如,下面是一个来自G-Kenya代码库里定义标题栏的布局,它可以被插到每个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>
根视图应该刚好和你在其他要插入这个视图的视图里相应位置一样。
使用 标签
在你要添加可复用布局的布局里,添加
<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 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>
现在,当你使用include标签插入这个布局到另一个布局时,系统会忽略merge标签,直接把两个Button替换到include标签的位置。