merge标签顾名思义就是用于布局合并的,通常与include标签配合使用。
include标签的简单使用可以查看这个连接:
android UI优化之include标签
然后这里来个自定义好了,若布局A include布局B,那么称布局A为外布局,被incude的布局B就称呼为内布局。我自己定义的,大家不要纠结了2333333
首先外布局activity_main.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:text="终极豪火球"
android:textSize="30sp" />
<!--内布局-->
<include layout="@layout/merge_layout" />
</RelativeLayout>
内布局merge_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/haohuoqiu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="豪火球"
android:textSize="30sp" />
<TextView
android:id="@+id/leiqie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="雷切"
android:textSize="30sp" />
</merge>
嗯,代码很简单,运行起来,使用UiAutomatorViewer查看布局层次,如下:
没用过UiAutomatorViewer的童鞋可以看看这个链接:
Android工具使用之UiAutomatorViewer
可以看出,内布局的内的控件直接加入到外布局中,这样就可以减少局部嵌套,加快绘制速度,达到优化的目的。
然后下面展示一个错误的merge用法,这里外布局不变,只改变内布局,如下:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/haohuoqiu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="豪火球"
android:textSize="30sp" />
<TextView
android:id="@+id/leiqie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="雷切"
android:textSize="30sp" />
</RelativeLayout>
</merge>
这次子内布局中,我在merge标签中加了一个RelativeLayout,也就是跟外布局的根节点都是RelativeLayout,但是最终的结果是,内布局的RelativeLayout是不会被忽略被merge,运行结果如下图:
最后对merge标签的使用作一个总结:
1、当你内布局的根节点和外布局的根节点是一样的话,那你可以把内布局的根节点直接替换为merge,这样最终的效果是一样的,而且还能减少一层布局的嵌套
2、merge标签必须是布局文件的根节点,否则运行会报如下错误:
<merge /> must be the root element
3、merge标签的属性是无用的,所以layout_width这些属性就不用写了。