1、优化原因
- 优化原因:影响页面的测量和绘制时间,从而影响页面的显示速度。
2、优化方案
1、选择消耗性能低的布局。
2、减少布局层级。
3、布局复用。
4、减少测量绘制时间。
1.选择消耗性能少的布局
1、性能消耗低:FrameLayout、LinearLayout、ConstraintLayout
2、性能消耗高:RelativeLayout
2.布局层级少
1、使用 merge 标签
2、布局层级少优于嵌套性能消耗低布局(如:1个RelativeLayout > LinearLayout 嵌套)
注意点:1.merge 必须放在布局文件根节点。2.merge 的布局会受到父布局类型的影响(merge 中使用 android:layout_below属性,父布局是 LinearLayout,属性会失效)。
// layout1.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button01"
android:textAllCaps="false" />
<include layout="@layout/layout2" />
</android.support.v7.widget.LinearLayoutCompat>
// layout2.xml 布局冗余
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button02"
android:textAllCaps="false" />
</android.support.v7.widget.LinearLayoutCompat>
// layout2.xml 优化布局
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button02"
android:textAllCaps="false" />
</merge>
3.布局复用
1、使用 include 标签
2、自定义布局复用
4.减少测量绘制时间
1、使用 ViewStub 标签(按需加载)
2、尽可能少用布局属性 wrap_content
注意点:
1.ViewStub 中的 layout 布局不能使用 merge 标签,会报错。
2.ViewStub 只可以 Inflate一次,多次 Inflate 会报错。
3.View.setVisible(View.GONE):父布局 inflate 时仍会被解析;ViewStub:父布局 inflate 时不会被解析。
<ViewStub
android:id="@+id/ViewStub"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout="@layout/layout3"/>
// 1、viewStub.inflate()或viewStub.setVisibility(View.VISIBLE) 按需加载布局
ViewStub viewStub = findViewById(R.id.ViewStub);
viewStub.inflate();
// 2、使用布局控件
btn03 = findViewById(R.id.btn03);
3、布局调优工具
1、Layout Inspector :Androidstudio3.0 布局检查工具。
2、Lint:Androidstudio 代码扫描分析工具。
- Layout Inspector 使用
- Lint 使用:https://blog.youkuaiyun.com/u011240877/article/details/54141714