一、Android UI渲染机制
人眼所能感觉到流畅的画面,最佳帧数为60帧每秒。在Android中,系统通过VSYNC信号触发对UI的渲染以及重绘,间隔时间为16ms,其实就是1000ms内显示60帧,每帧花费的时间1000/60,如果系统发出VSYNC信号16ms无法绘制,就会丢弃该帧,继续下一次信号,这就是画面卡顿的原因。
二、布局优化
1、选择性能消耗较小的布局
性能消耗FrameLayout、LinearLayout < RelativeLayout。
2、减少布局嵌套层级
尽量用最少的布局层级完成布局,去除无用布局。
3、使用标签
一个程序一般为了风格统一,很多界面会有共通的UI,标签可以将一个指定的布局文件加载到当前的布局文件中。我们可以定义这个通用UI,使用标签添加这个通用UI的引用。
如:存在通用布局layout_a.xml
xmlns:android="/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tv1"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tv2"/>
在布局layout_b.xml中引用layout_a.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
layout="@layout/layout_a" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tv3"/>
4、使用标签
标签一般与标签一起使用以减少布局层数,如上面的layout_a是一个竖直方向的线性布局,而layout_b也是一个竖直方向的线性布局,很明显layout_a的线性布局是多余的,这时候就可以使用标签包裹去掉一层布局。
xmlns:android="/apk/res/android">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tv1"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tv2"/>
5、使用实现View的延迟加载
ViewStub继承自View,不可见且大小为0,可以做到在使用的时候再加载,提高程序初始化性能。
android:id="@+id/vs"
android:layout="@layout/layout_b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
在需要加载布局的时候
ViewStub vs = findViewById(R.id.vs);
vs.inflate();
//或者
vs.setVisibility(View.VISIBLE);
6、移除多余背景
(1)如根布局背景为白色,子布局就不需要再设置白色背景
(2)移除系统主题默认的window背景
image
三、总结
1、选择性能消耗较小的布局
2、减少布局嵌套层级
3、使用标签
4、使用标签
5、使用
6、移除多余背景