Android 性能优化 四 布局优化merge标签的使用

小白:之前分享了ViewStub标签的使用,Android还有其他优化布局的方式吗?

小黑:<merge />标签用于减少View树的层次来优化Android的布局。先来用个例子演示一下:

首先主需要一个配置文件activity_main.xml

<RelativeLayout 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="wrap_content"
    android:layout_height="wrap_content"
    android:text="merge标签使用" />

</RelativeLayout>

再来一个最简单的Activity,文件名MainActivity.java

package com.example.merge;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
     }
}

小白:按着上面的代码创建工程,运行后使用“DDMS -> Dump View Hierarchy for UI Automator”工具,截图如下

merge 使用前

小黑:最下面两层RelativeLayout与TextView就是activity_main.xml布局中的内容,上面的FrameLayout是Activity setContentView添加的顶层视图。下面使用merge标签可以查看下区别

布局文件activity_main.xml修改内容如下:

<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="wrap_content"
    android:layout_height="wrap_content"
    android:text="merge标签使用" />

</merge>

小白:使用“DDMS -> Dump View Hierarchy for UI Automator”工具,截图如下

merge使用后

小黑:FrameLayout下面直接就是TextView,与之前的相比少了一层RelativeLayout而实现的效果相同。

某些时候,自定义可重用的布局包含了过多的层级标签,比如我们

例如:这样的话,使用<include>包含上面的布局的时候,系统会自动忽略merge层级,而把两个button直接放置与include平级

小白:什么情况考虑使用Merge标签?

小黑:一种是向上面的例子一样,子视图不需要指定任何针对父视图的布局属性,例子中TextView仅仅需要直接添加到父视图上用于显示就行。

另外一种是假如需要在LinearLayout里面嵌入一个布局(或者视图),而恰恰这个布局(或者视图)的根节点也是LinearLayout,这样就多了一层没有用的嵌套,无疑这样只会拖慢程序速度。而这个时候如果我们使用merge根标签就可以避免那样的问题,官方文档 Android Layout Tricks #3: Optimize by merging  中的例子演示的就是这种情况。

小白: <merge />标签有什么限制没?

小黑: <merge />只能作为XML布局的根标签使用。当Inflate以<merge />开头的布局文件时,必须指定一个父ViewGroup,并且必须设定attachToRoot为true。

小黑:merge标签还有一些属性可供使用,具体可以查看API文档,例如android:layout_width、 android:layout_height等

原文地址:https://www.cnblogs.com/xiaorenwu702/p/5176714.html