Android性能优化——标签

昨天小米5发布(cpu 高通骁龙820,RAM 4GB)现在的工业水平来看 内存跟性能足够高了。。。

作为开发者来讲 我们做的应用 要极致,要优雅。

Merge 标签用于减少View树的层次来优化Android的布局。
下面来做个简单的示例 查看界面的层级验证一下 Merge 标签 的效果。

示例:

主页面:activity_main.xml (包含了 layout_merge.xml 布局)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">

  <ImageView  android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" />

  <include layout="@layout/layout_merge" />
</LinearLayout>

布局页面:layout_merge.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
    <TextView  android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:text="这是 lyaout_merge " />
</RelativeLayout>

按着上面的代码创建工程,运行后使用“DDMS -> Dump View Hierarchy for UI Automator”工具,界面层级如下:
Android性能优化——<merge>标签_第1张图片

可以看出最下面的两层 RelativeLayout 和 TextView是layout_merge.xml的内容。下面使用merge标签可以查看下区别。
布局文件 layout_merge.xml 修改如下:

<merge xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
    <TextView  android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:text="这是 lyaout_merge " />
</merge>

使用“DDMS -> Dump View Hierarchy for UI Automator”工具,界面层级如下:
merge使用后:
Android性能优化——<merge>标签_第2张图片

与之前的相比少了一层RelativeLayout而实现的效果相同。
使用 include 包含布局时,会自动忽略掉merge这一层,如上:TextView会与include同级, layout_merge.xml 内的 TextView会直接成为 activity_main.xml的子view, TextView会直接继承 LinearLayout 的属性。
同理如果 activity_main.xml的父布局 换成RelativeLayout 或者Framelayout,TextView会继承RelativeLayout 或者Framelayout 位置也相应被改变。
如:activity_main.xml改成RelativeLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">

  <ImageView  android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" />

  <include layout="@layout/layout_merge" />
</RelativeLayout>

那么TextView的位置也就变了
Android性能优化——<merge>标签_第3张图片

使用场景:

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

注意点:

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

参考:

布局优化
Android开发艺术探索 第十五章 第一节

你可能感兴趣的:(android,性能优化,布局优化,android性能,Android优化)