天天看点

layout 中include和merge标签的使用

  • 使用<include /> 标签来重用layout代码

如果在一个项目中需要用到相同的布局设计,可以通过<include /> 标签来重用layout代码,该标签在android开发文档中没有相关的介绍。在launcher中 用到了这个标签:

<com.android.launcher.Workspace
  android:id="@+id/workspace"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  launcher:defaultScreen="1">
  <include android:id="@+id/cell1" layout="@layout/workspace_screen" />
  <include android:id="@+id/cell2" layout="@layout/workspace_screen" />
  <include android:id="@+id/cell3" layout="@layout/workspace_screen" />

</com.android.launcher.Workspace>      
这样就可以重复的应有workspace_screen的代码而不用通过复制,粘贴。incude中有对应的一些属性。入上面的android:id 这样的就通过 id可以访问到workspze_screen中的其他      
的控件等。      
  • 使用<merge /> 标签来减少视图层级结构
在Android layout文件中需要一个顶级容器来容纳其他的组件,而不能直接放置多个组件      
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent">

    <ImageView

        android:layout_width="fill_parent"

        android:layout_height="fill_parent" 

        android:scaleType="center"

        android:src="@drawable/golden_gate" />

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Golden Gate" />

</FrameLayout>



       
上面的代码显示一个图片,然后在图片上方显示一个title, 结果如下图:

        
layout 中include和merge标签的使用
android activity的默认布局为FrameLayout,这样上面的布局代码就有2层FrameLayout,通过HierarchyViewer 工具看到的结构如下:
layout 中include和merge标签的使用
如果能在layout文件中把FrameLayout声明去掉就可以进一步优化布局代码了。 但是由于布局代码需要外层容器容纳,如果 直接删除FrameLayout则该文件就不是合法的布局文件。这种情况下就可以使用<merge /> 标签了。 修改为如下代码就可以消除多余的FrameLayout了:
<merge xmlns:android="http://schemas.android.com/apk/res/android">     <ImageView         android:layout_width="fill_parent"         android:layout_height="fill_parent"          android:scaleType="center"         android:src="@drawable/golden_gate" />     <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Golden Gate" /> </merge>

继续阅读