美文网首页
Android性能优化之界面优化总结

Android性能优化之界面优化总结

作者: 丶切切切切梨 | 来源:发表于2019-05-14 00:05 被阅读0次

一、Android UI渲染机制

人眼所能感觉到流畅的画面,最佳帧数为60帧每秒。在Android中,系统通过VSYNC信号触发对UI的渲染以及重绘,间隔时间为16ms,其实就是1000ms内显示60帧,每帧花费的时间1000/60,如果系统发出VSYNC信号16ms无法绘制,就会丢弃该帧,继续下一次信号,这就是画面卡顿的原因。

二、布局优化

1、选择性能消耗较小的布局

性能消耗FrameLayout、LinearLayout < RelativeLayout。

2、减少布局嵌套层级

尽量用最少的布局层级完成布局,去除无用布局。

3、使用<include>标签

一个程序一般为了风格统一,很多界面会有共通的UI,<include>标签可以将一个指定的布局文件加载到当前的布局文件中。我们可以定义这个通用UI,使用<include>标签添加这个通用UI的引用。

如:存在通用布局layout_a.xml

<?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="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tv1"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tv2"/>
</LinearLayout>

在布局layout_b.xml中引用layout_a.xml

<?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="match_parent"
    android:orientation="vertical">

    <include android:id="@+id/include_layout"
              layout="@layout/layout_a" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tv3"/>
</LinearLayout>

4、使用<merge>标签

<merge>标签一般与<include>标签一起使用以减少布局层数,如上面的layout_a是一个竖直方向的线性布局,而layout_b也是一个竖直方向的线性布局,很明显layout_a的线性布局是多余的,这时候就可以使用<merge>标签包裹去掉一层布局。

<?xml version="1.0" encoding="utf-8"?>
<merge
    xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tv1"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tv2"/>
</merge>

5、使用<ViewStub>实现View的延迟加载

ViewStub继承自View,不可见且大小为0,可以做到在使用的时候再加载,提高程序初始化性能。

    <ViewStub
        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、使用<include>标签

4、使用<merge>标签

5、使用<ViewStub>

6、移除多余背景

相关文章

网友评论

      本文标题:Android性能优化之界面优化总结

      本文链接:https://www.haomeiwen.com/subject/ijadaqtx.html