您的位置:首页 > 移动开发 > Android开发

Android应用开发之性能优化3:merge标签

2015-03-02 09:11 225 查看
之前在开发中我也没有用过merge这个标签,后来经同事给我讲了下,我就尝试着用了merge标签,发现这个标签对应用布局优化确实有很大的帮助。今天就简单讲下这个标签的用法。说到<merge />标签对应用的优化主要是优化UI结构:通过删减多余或者额外的层级,从而优化整个Android 应用中Layout布局的结构。

将通过一个例子来了解这个标签实际所产生的作用,这样可以更直观的了解<merge/>的用法。不过在用的时候我们要注意:

1,<merge />只可以作为 layout布局中xml文件内容的根节点,就像把我们平时用的根结点LinearLayou,RelativeLayout等换成merge。

2,如果需要扩充的 layout布局中xml文件本身是由merge作为根节点的话,则需要将被导入的layout布局置于 viewGroup中(外面套一个ViewGroup类控件),同时需要设置属性attachToRoot为True。

3,最简单最常用的用法:如果我们使用 FrameLayout 作为 activity's content view 的父元素(也就是在 main.xml 里把它写在最外层) ,那么可以 考虑用<merge />替换<FrameLayout />,从而可以减少一层结构达到优化效果。

下面代码是一个简单的Layout布局,包含两个Views元素:ImageView和TextView 。默认状态下我们将这两个元素放在FrameLayout中:在主视图中全屏显示一张图片,之后将标题显示在图片上,并位于视图的下方:

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent">



<ImageView

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scaleType="center"

android:src="@drawable/my_back" />



<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginBottom="20dip"

android:layout_gravity="center_horizontal|bottom"

android:padding="10dp"

android:background="#AA000000"

android:textColor="#ff00ff"

android:textSize="16sp"

android:text="MERGE标签使用" />



</FrameLayout>

我们直接将上边xml代码中的framLayout替换成merge:

<?xml version="1.0" encoding="utf-8"?>

<merge xmlns:android="http://schemas.android.com/apk/res/android">



<ImageView

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scaleType="center"

android:src="@drawable/my_back" />



<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginBottom="20dip"

android:layout_gravity="center_horizontal|bottom"

android:padding="12dip"

android:background="#AA000000"

android:textColor="#ff00ff"

android:textSize="16sp"

android:text="MERGE标签使用" />



</merge>

这样就可以了,运行程序后在Emulator中显示的效果是一样的,可是通过hierarchyviewer查看的UI结构是有变化的,当初多余的FrameLayout节点被合并在一起了,或者可以理解为将merge标签中的子集直接加到Activity的FrameLayout跟节点下(这里需要提醒大家注意:所有的Activity视图的根节点都是frameLayout)。如果你所创建的Layout并不是用framLayout作为根节点(而是应用LinerLayout等定义root标签),就不能应用上边的例子通过merge来优化UI结构。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: