布局是一个App很是关键的一部分,布局性能的好坏可直接影响到用户的体验。试想下若是一个RecyclerView
滑动时异常卡顿,那用户估计也没有心情去住下滑了,可能就直接强制杀掉App了去,而后回过头去应用商店给个差评“卡的不要不要的”。虽然如今手机内存、CPU等各项性能都上来了看起来很强,实际上仍是卡的不行,因此咱们仍是要多学习下性能优化
方面的知识。java
本文将分三个部分来介绍Android布局
优化的相关知识:android
优化布局的层级是很是重要,你们都知道Android的布局元素主可分为View和ViewGroup,其余LinearLayout、FrameLayout都是ViewGroup的子类。每一个View在显示以前都会有测量(measure)
、布局(layout)
、绘制(draw)
这三步,布局层次越深相应的带来的层级遍历的消耗就越多。要优化布局的层级可使用Layout Inspector
来分析某个View的测量、布局、绘制所消耗的时间,帮助开发时定位布局性能较差的点。性能优化
使用Layout Inspector
很是方便,只须要简单的几步就能使用:bash
Layout Inspector
分析完成就能够查看各项数据了。以下图所示Layout Inspector
的主界面可分为三个部分:布局
使用Layout Inspector
分析布局层次后就能够对布局的层次作一些改动,如下是一些小技巧你们可参考优化布局层级:性能
merge
标签compound drawable
布局重用是开发过程当中很是重要的一部分,这样能减小多余的布局文件和维护成品。在Android中布局重用可使用<include>
标签,它能够高效重用完整的布局,好比有多个Activity中都有一个底部的Button
除了文字不一样之外其他的样式都基本相同,这样只须要创建一个底部按钮布局文件,而后在Activity的布局中经过<include>
标签引用按钮的布局就能够实现一个统一按钮。学习
根据上面提到的例子新建一个layout_bottom_button.xml
的布局文件:优化
<?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="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:background="@android:color/white"```
<include
layout="@layout/layout_bottom_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="5dp"
android:background="#36b7f7"
android:textColor="@android:color/white"
tools:text="下一步"
/>
</FrameLayout>
复制代码
而后再创建一个新的布局文件,使用<include>
标签包含上面的布局:spa
<?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">
<include layout="@layout/layout_bottom_button"/>
</FrameLayout>
复制代码
只须要简单几步就能实现布局的重用,同时还能够从新覆盖布局参数:code
<include
layout="@layout/layout_bottom_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
复制代码
须要注意的是,覆盖布局参数时必须要覆盖layout_width
和layout_height
这两个参数。
有些时候布局会须要一些其它的View
,但它们不是一开始就显示到界面上,好比进度条、提示消息等元素,它们只会在特色的场景下才会出现,相似这样的场景可使用<ViewStub>
标签来处理在须要的时候加载View
。
ViewStub
是一个轻量级的View
,它不会显示到界面上,它只会在你须要的时候加载将布局加载到布局层次中。ViewStub
的使用很是简单只须要一个android:layout
属性来指定须要替换的布局文件就能够了:
<ViewStub android:id="@+id/stub_import" android:inflatedId="@+id/panel_import" android:layout="@layout/progress_overlay" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" />
复制代码
当你须要加载android:layout
指定的布局文件时,只须要调用setVisibility(View.VISIBLE)
或inflate()
方法就能将ViewStub
替换成android:layout
指定的布局:
findViewById(R.id.stub_import).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
复制代码
用setVisibility(View.VISIBLE)
或inflate()
方法后,ViewStub
将再也不是布局层次中的一部分,它会被android:layout
指定的布局文件替换掉。