前言
优化的思想:尽量减少布局文件的层级和降低Overdraw来减轻CPU和GPU负载。
再贴下CPU和GPU的工作,潜在的问题,检测的工具和解决方案图:
解决方案
一、 Layout优化
我们可以在Layout设计时考虑移除层级和删除无用的控件。
还可以通过通过Hierarchy Viewer去检测渲染效率,去除不必要的嵌套。
1. Layout 设计优化
在布局设计时,就应该考虑最优化思想。下面列出一些常用的技巧:
- 有选择地使用性能较低的ViewGroup.比如不嵌套的情况下,用LinearLayout和FrameLayout代替RelativeLayout.
- RelativeLayout功能比较复杂,布局过程需要花费更多的CPU时间
- 但是如果要LinearLayout嵌套来代替RelativeLayout,还是建议用RelativeLayout。因为嵌套同样会降低程序的性能
- 使用include实现布局重用,避免代码重复
- 使用merge减少布局层级结构
- 使用ViewStub实现延时加载
- 在TextView中使用Compound drawable,取代ImageView + TextView
- 使用LinearLayout自带的分割线: android:divider=”“
2. Hierarchy Viewer工具优化布局
如果找不到Hierarchy Viewer,可以看下面的“如何找到Hierarchy Viewer?”
示例layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Version 1. Uses nested LinearLayouts -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="@+id/avatar1"
android:layout_width="@dimen/avatar_dimen"
android:layout_height="@dimen/avatar_dimen"
android:layout_margin="@dimen/avatar_layout_margin"
android:onClick="hideOffline" />
<include layout="@layout/offline" />
</LinearLayout>
<!-- Version 2: uses a single RelativeLayout -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/avatar2"
android:layout_width="@dimen/avatar_dimen"
android:layout_height="@dimen/avatar_dimen"
android:layout_margin="@dimen/avatar_layout_margin"
android:onClick="showOffline" />
<ViewStub
android:id="@+id/offline_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/avatar2"
android:layout="@layout/offline" />
</RelativeLayout>
</LinearLayout>
上面的布局文件展示了两种写法:一个是Linearlayout嵌套的,一个是RelativeLayout搭配StubView
从图中来看方案二教快一些(可以多次点击Profile Node取样)。Hierarchy Viewer 分析图示:
点击LinearL