性能优化(四)Google典范之Render实践

本文探讨了Android应用性能优化中的布局优化和Overdraw解决方案。通过Layout设计优化,如减少层级、使用Hierarchy Viewer工具,以及移除不必要的背景和巧妙使用clipRect,可以显著提升UI性能。同时,避免在onDraw方法中执行大量操作也是关键。
摘要由CSDN通过智能技术生成

前言

优化的思想:尽量减少布局文件的层级和降低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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值