Android 布局优化 Merge的使用

本小妞迷上赌 提交于 2019-11-29 06:27:25

一、Merge的作用
The 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标签设置的所有属性都是无效的

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!