内容转自:http://fengweipeng1208.blog.163.com/blog/static/21277318020138229754135/ 在我们开发android布局时,经常会有很多的布局是相同的,这个时候我们可以通过<include/>和< ...
内容转自:http://fengweipeng1208.blog.163.com/blog/static/21277318020138229754135/
在我们开发android布局时,经常会有很多的布局是相同的,这个时候我们可以通过<include/>和<merge/>标签实现将复杂的布局包含在需要的布局中,减少重复代码的编写。
1. 创建一个可以重复使用的布局:
如下代码描述在应用中每个acitivity都出现的顶栏titlebar.
1 <FrameLayout ="http://schemas.android.com/apk/res/android" 2 android:layout_width=”match_parent” 3 android:layout_height="wrap_content" 4 android:background="@color/titlebar_bg"> 5 6 <ImageView android:id="@+id/title" 7 android:layout_width="wrap_content" 8 android:layout_height="wrap_content" 9 android:src='/images/loading.gif' data-original="@drawable/gafricalogo" />10 </FrameLayout>
那么,绿色的代码设置的属性是有效的,红色的代码设置的属性是无效的。
其实,这很容易理解,就是include是为了复用一段封装好的布局,那么,布局内部的东西自然是不用改的,如果要改,还不如在被引用的文件中改好,我们在include中修改的只是被引用的布局的大小位置。
3. 使用<merge/>标签
merge标签用来消除我们在include一个布局到另一个布局时所产生的冗余view group。比如现在很多布局中会有两个连续的Button,于是我们将这两个连续的Button做成可复用布局(re-usable layout)。在使用include标签时我们必须先将这两个Button用一个view group比如LinearLayout组织在一起然后供其它布局使用,如果是include的地方也是LiearLayout就会造成有两层连续的LiearLayout,除了降低UI性能没有任何好处。这个时候我们就可以使用<merge/>标签作为可复用布局的root view来避免这个问题。
1 <merge ="http://schemas.android.com/apk/res/android"> 2 3 <Button 4 android:layout_width="fill_parent" 5 android:layout_height="wrap_content" 6 android:text="@string/add"/> 7 8 <Button 9 android:layout_width="fill_parent" 10 android:layout_height="wrap_content"11 android:text="@string/delete"/>12 13 </merge>
原标题:【转】在Android布局中使用include和merge标签
关键词:Android
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。