需要注意的是:只可以作为xml layout的根节点,当需要扩充的xml layout本身是由merge作为根节点的话,需要将被导入的xml layout置于 viewGroup中,同时需要设置attachToRoot为True。关于 attachToRoot ,在自定义 View 的时候有一句代码:LayoutInflater.from(parent.getContext).inflater(R.layout.xxx, parent, true),这段代码最后一个参数 true,就是讲 attachToRoot 设置为 true。
前言:使用是为了避免嵌套过多无用布局,嵌套的布局会让View Tree的高度越来越高,所以应该尽量减少布局的层级来优化布局
应用场景:
1、FrameLayout作为界面的根布局时,可以用标签作为根节点,因为Activity默认的布局是FrameLayout
如果不使用标签而是直接使用
<FrameLayout 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" >
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="imageView1" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="textView1" />
</FrameLayout>
这样的话UI结构视图就为:
而如果使用标签
<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="textView1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button1" />
</merge>
UI结构视图就为:
很明显如果用就会多出一个节点造成了资源浪费
2.如果用RelateLayout或Linearlayout作为界面根布局时,界面中一些可复用的或逻辑独立的布局用或者ViewStub标签从外部导入xml结构时,如果include布局再使用RelateLayout或Linearlayout就没意义了。这时布局可以考虑用标签作为根节点优化。
用法:
<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="textView1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button1" />
</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_include" />
</LinearLayout>
或者
<RelateLayout 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_include" />
</RelateLayout>