Improving Layout Performance(二)
本文出处:http://developer.android.com/training/improving-layouts/reusing-layouts.html
Re-using Layouts with <include/>
为了提高你的Layouts的复用性,你也可以使用<include/> 和 <merge/> 标签内嵌一个布局到另一个布局里。
布局重用是十分强大的,能让你产生可重用的复杂布局。例如,一个 yes/no按钮面板,或者有描述文本的自定义进度条。那即是在你的应用里,各个布局里通有的共性的元素能抽取出来、独自里管理。然后被其他的需要的Layout引入。因此,当你写自定义的View产生UI组件时,你能作为一个Layout文件更容易复用它。
Create a Re-usable Layout
如果你已经知道某个布局需要复用,产生一个新的XML布局文件,定义这个Layout.例如,这是一个来自于G-Kenya代码库的布局。定义了一个title bar。文件名为(titlebar.xml),被包含在每个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>
Use the <include> Tag
在你想要引用可重用组件的布局里加入<include/>标签。例如,这是一个来自于G-Kenya 代码库的布局文件。该文件include进了上述的titlebar.xml
<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>
在<include/>标签里,你也能重写所有的layout参数(任何android:layout_*属性),例如:
<include android:id=”@+id/news_title”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
layout=”@layout/titlebar”/>
然而,如果你想要用<include>标签重写布局属性,为了其他的布局属性能生效,你必须要同时重写android:layout_height和android:layout_width属性。
Use the <merge> Tag
某些时候,自定义可重用的布局包含了过多的层级标签,比如我们需要在LinearLayout里面嵌入一个重用的组件,而恰恰这个自定义的可重用的组件根节点也是LinearLayout,这样就多了一层没有用的嵌套,无疑这样只会拖慢程序速度。而这个时候如果我们使用merge根标签就可以避免那样的问题。例如:
<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平级