Android性能优化之布局优化
1、屏幕的UI刷新机制
//todo
2、布局选择
//todo
3.优化标签使用
3.1 include标签(布局重用)使用include标签,将另一个xml文件引入,作为布局的一部分。include的最大的作用是便于布局重用(比如我们所有的界面的标题栏都是一样的)
3.2 merge标签主要用于删除多余的层级避免嵌套过多无用的布局,减少布局的深度。用一个非常简单的布局来说明merge标签的使用。就在界面上显示一个TextView。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:text="就一个布局"
android:textColor="@android:color/holo_red_dark"/>
</FrameLayout>
merge标签,然后再里面放TextView
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:text="就一个布局"
android:textColor="@android:color/holo_red_dark"/>
</merge>
前后对比,发现使用merge的时候层级确实少了一层(少了FrameLayout)。
merge使用场景
Activity layout文件的根视图是FrameLayout的时候
因为我们在Activity中setContentView()的content对应的就是一个FrameLayout。所以当我们布局文件的根视图也是FrameLayout的时候完全可以使用merge标签来减少一层FrameLayout结构。
merge标签配合自定义组合布局ViewGroup的使用
自定义组合控件ViewGroup的时候,可以使用merge来减少一层ViewGroup。比如自定义继承LinearLayout的组合控件,建议让自定义View的layout布局文件根节点设置成merge。
merge标签配合include标签使用
include标签使用的时候要注意merge标签的使用。可能某些情况下merge标签可以派上用场。接下来我们来改造一下文章前面include标签的实例。layout_title.xml文件我们完全可以使用merge标签来减少RelativeLayout的层级。
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_title"
android:layout_width="match_parent"
android:layout_height="42dp"
android:gravity="center"
android:background="@color/colorPrimary"
android:text="标题"
android:textSize="18sp"
android:textColor="@android:color/white"/>
</merge>
并不是说include标签使用的时候都可以用merge标签来优化布局哦。也是要根据实际情况来确定的。
merge使用的时候有几点是要特别注意的
- merge必须放在布局文件的根节点上。
- merge并不是一个ViewGroup,也不是一个View,它相当于声明了一些视图,等待被添加。
- merge标签被添加到A容器下,那么merge下的所有视图将被添加到A容器下。
- 因为merge不是View,所以对merge标签设置的所有属性都是无效的。
3.3 ViewStub标签
ViewStub使用延迟加载的方式,避免资源的浪费,减少渲染时间,在需要的时候才加载View。即使将其放置于布局文件中,如果没有进行加载那就为空,不像其它控件一样只要布局文件中声明就会存在。比如有这么个情况,网络请求的界面网络成功显示内容信息,网络请求失败显示失败的界面。试想一下,如果网络状况良好,并不需要加载失败页面。这个时候使用ViewStub是一个非常好的选择。
ViewStub新增的属性
- android:layout:设置ViewStub被inflate的布局控件。ViewStub的内容布局。
- android:inflateId:重写ViewStub的父布局控件的Id。
ViewStub使用的时候我们一般使用inflate()或者setVisibility(View.VISIBLE)使ViewStub可见。但是咱们还得注意,当setVisibility(int)或inflate()方法被调用之后,这个ViewStub在布局中将被使用指定的View(android:layout内容)替换。而且inflate过一遍的ViewStub,如果被隐藏之后再次想要显示,将不能使用inflate()方法,但是可以再次使用setVisibility(int)方法设置为可见。
ViewStub inflate()函数只能调用一次,重复调用会导致异常,这是因为ViewStub只要加载过一次,其自身就会被移除,把并自身所包含的内容全部传给父布局。
ViewStub所替代的layout文件中不能使用merge标签。
4、原生View控件优化
常见原生View优化,ListView分页加载
WebView优化
全局WebView、客户端代理请求数据、优化网页加载速度