Android性能优化3--提升Layout的性能

Layout 是 Android 应用中直接影响用户体验的关键部分。如果实现的不好,你的 Layout 会导致程序非常占用内存并且 UI 运行缓慢。

优化Layout的层级

经验总结,嵌套层次超过所谓的10层,性能急剧下降,所以被认为陷入深度不超过10。


检查 Layout

Android SDK 工具箱中有一个叫做 Hierarchy Viewer 的工具,能够在程序运行时分析 Layout。你可以用这个工具找到 Layout 的性能瓶颈。



使用<include/>标签重用Layout

创建可重用 Layout

如果你已经知道你需要重用的 Layout,就先创建一个新的 XML 文件并定义 Layout 。比如,以下是一个来自 G-Kenya codelab 的 Layout,定义了一个需要添加到每个 Activity 中的标题栏(titlebar.xml):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width=”match_parent”
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg">

    <ImageView android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/gafricalogo" />
</FrameLayout>

根节点 View 就是你想添加入的 Layout 类型。

使用<include>标签

使用 <include> 标签,可以在 Layout 中添加可重用的组件。比如,这里有一个来自 G-Kenya codelab 的 Layout 需要包含上面的那个标题栏:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:background="@color/app_bg"
    android:gravity="center_horizontal">

    <include layout="@layout/titlebar"/>

    <TextView android:layout_width=”match_parent”
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />

    ...

</LinearLayout>

猜你喜欢

转载自blog.csdn.net/haobobo710/article/details/80900010
今日推荐