关于<merge/>

来源:互联网 发布:中国海外并购数据 编辑:程序博客网 时间:2024/06/06 02:47

1.merge是啥:

它是android提供给我们的一个布局标签,它具备的功能是:“减少视图层级,从而降低UI渲染性能的消耗”
那究竟是如何减少层级的呢?

2.最简单的merge使用例子:

布局 mergeshow.xml

<?xml version="1.0" encoding="utf-8"?><merge xmlns:android="http://schemas.android.com/apk/res/android">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="I am Merge Tv"/></merge>

在MainActivity当中去加载这个布局是能显示出来的,显示效果如下:

可能有的同学一看这布局就和小弟一样直接就蒙B了,从接触android以来,布局文件顶部从来都是一大堆的什么LinlearLayout,RelaytiveLayout,现在突然蹦出个merge来感觉接受无能。后俩经过一番的资料查询,我的理解是:“当LayoutInflater检测到merge标签的时候,会自动取出其中的布局元素,贴到上一层的父布局当中。”,体现在本例中,便是将其中的TextView直接贴到Activity的DecorView当中(我们知道DecorView就是一个FrameLayout),现在再来回忆一下之前我们写布局的方式。

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"    android:orientation="vertical"    tools:context="bv.zj.com.mergetviewstubdemo.MainActivity">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!" /></LinearLayout>

对比二者,是不是省去了一层LinearLayout?
当然这只是我们的推论,想要眼见为实,则需要用android视图调试工具HierarchyViewer,关于该工具的使用,本文就不讨论了,想要了解的同学可以戳这里。

3.merge的限制:

  • 只能作为XML布局的根标签使用
  • 当Inflate以开头的布局文件时,必须指定一个父ViewGroup,并且必须设定attachToRoot为true(参看inflate(int, android.view.ViewGroup, Boolean)方法)。

THANKS:

http://www.cnblogs.com/travelfromandroid/articles/2133206.html
http://blog.csdn.net/xyz_lmn/article/details/14524567