一、前言:
Merge的作用
The <merge /> tag helps eliminate redundant view groups in your view hierarchy when including one layout within another.
大意是,merge标签是用来帮助在视图树中减少重复布局的,当一个layout包含另外一个layout时。
二、示例
- 不使用merge
layout1.xml
<FrameLayout>
<include layout="@layout/layout2"/>
</FrameLayout>
layout2.xml:
<FrameLayout>
<TextView />
</FrameLayout>
实际效果:
<FrameLayout>
<FrameLayout>
<TextView />
</FrameLayout>
</FrameLayout>
- 使用merge
layout1.xml
<FrameLayout>
<include layout="@layout/layout2"/>
</FrameLayout>
layout2.xml:
<merge>
<TextView />
</merge>
实际效果:
<FrameLayout>
<TextView />
</FrameLayout>
三、要点
- merge必须放在布局文件的根节点上。
- merge并不是一个ViewGroup,也不是一个View,它相当于声明了一些视图,等待被添加。
- merge标签被添加到A容器下,那么merge下的所有视图将被添加到A容器下。
- 因为merge标签并不是View,所以在通过LayoutInflate.inflate方法渲染的时候, 第二个参数必须指定一个父容器,且第三个参数必须为true,也就是必须为merge下的视图指定一个父亲节点。
- 因为merge不是View,所以对merge标签设置的所有属性都是无效的。
四、心得
- 可以在使用组合控件形式的自定义view中使用。以前不了解merge时的做法是,创建类,继承RelativeLayout,然后创建layout.xml,根布局也是RelativeLayout,在然后在布局中写入其他控件,接着就是在自定义view中inflate布局进来,之后巴拉巴拉一堆逻辑。
所以应该在xml布局中根节点可以使用merge来减少重复RelativeLayout布局。 - 在AS中无法预览怎么办?使用parentTag指定被装在的parent的布局容器类型,例如 tools:parentTag="android.widget.FrameLayout",那么就可以预览到当前布局被装在进FrameLayout时候的效果
网友评论