1、Hierarchy Viewer
打开Android Device Monitor-添加Hierarchy Viewer窗口
运行app选中相应进程,可以观察到View层级中的每一个View的属性
提升布局性能的关键点是尽量保持布局层级的扁平化,避免出现重复的嵌套布局
举个例子:下面分别用LinearLayout和RelativeLayout实现同样的布局
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:src="@mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="this is text 1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="this is text 2"/>
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<ImageView
android:id="@+id/image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="this is text 1"
android:layout_toRightOf="@id/image"/>
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="this is text 2"
android:layout_toRightOf="@id/image"
android:layout_below="@id/text1"/>
</RelativeLayout>
使用Hierarchy Viewer观察性能
如果是一个层级不需要嵌套时,优先使用LinearLayout
View的绘制进行measure, layout, draw,分别对应onMeasure(), onLayout, onDraw()
RelativeLayout和LinearLayout性能差异主要在onMeasure()上
- RelativeLayout分别对所有子View进行两次measure,横向纵向分别进行一次
- LinearLayout只在使用weight属性进行布局时会对子View进行第两次measure
2、过度绘制
Overdraw(过度绘制),原因是屏幕上的某个像素在同一帧的时间内被绘制了多次。在多层次重叠的布局结构里面,如果不可见的部分也在做绘制的操作,会导致某些像素区域被绘制了多次,这样就会浪费大量的CPU以及GPU资源。
在手机设置里面的开发者选项,打开Show GPU Overdraw的选项,可观察UI上的Overdraw情况
蓝色、淡绿、淡红、深红代表了4种不同程度的Overdraw
1x过度绘制是蓝色、2x是绿色、3x是淡红、4x是深红
一般的解决方法:
- 移除不必要的背景色
- 按需加载布局,比如使用ViewStub来加载一些不常用的布局
- 减少布局层次