易采站长站为您分析Android中使用include标签和merge标签重复使用布局,文中讲解了创建可复用布局的例子以及include标签和merge标签使用例子,需要的朋友可以参考下
<FrameLayout xmlns:android="http://www.easck.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://www.easck.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"/>
尽管Android提供了各种组件来实现小而可复用的交互元素,你也可能因为布局需要复用一个大组件。为了高效复用完整布局,你可以使用<include/>和<merge/>标签嵌入另一个布局到当前布局。所以当你通过写一个自定义视图创建独立UI组件,你可以放到一个布局文件里,这样更容易复用。
复用布局因为其允许你创建可复用的复杂布局而显得非常强大。如,一个 是/否 按钮面板,或带描述文本的自定义进度条。这同样意味着,应用里多个布局里共同的元素可以被提取出来,独立管理,然后插入到每个布局里。
创建可复用布局
如果你已经知道哪个布局需要重用,就创建一个新的xml文件来定义布局。如,下面是一个来自G-Kenya代码库里定义标题栏的布局,它可以被插到每个Activity里:
复制代码<FrameLayout xmlns:android="http://www.easck.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://www.easck.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"/>










