前言:merge主要是进行UI布局的优化的,删除多余的层级,优化UI。<merge/>多用于替换frameLayout或者当一个布局包含另一个布局的时候,<merge/>标签用于消除师徒层次结构中多余的视图组。例如你的朱布局文件是垂直的,此时如果你引入一个垂直布局的<include>.这时如果include布局使用的LinearLayout就没意义了,使用的话反而减慢你的UI表现。这时可以使用<merge/>标签优化。<merge>标签也就是排除一个布局插入另一个布局产生的多余的viewgroup.
用法:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是button3" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是button2" />
</merge>
布局的效果<这里注意是frameLayout的效果>,为什么用在这里呢,因为android有一个默认的FrameLayout的布局
2.当把有<merge>标签的布局放在<include>中的时候,就会忽视<merge>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include layout="@layout/fragment_main" />
</LinearLayout>
效果
3.<merge>标签的限制
小白: <merge />标签有什么限制没?
小黑: <merge />只能作为XML布局的根标签使用。当Inflate以<merge />开头的布局文件时,必须指定一个父ViewGroup,并且必须设定attachToRoot为true。