Android性能优——布局优化
总结:提升UI的可复用性,减少嵌套,提高UI的渲染速度。
- RelativeLayout比LinearLayout要好
- Listview少用layout_weight属性
- 利用include复用
- ViewStub隐藏不常用的控件
- merge减少嵌套层次,配合include天衣无缝
include标签
include标签常用于将布局中的公共部分提取出来,比如我们要在activity_main.xml中需要上述LinearLayout的数据,那么就可以直接include进去了。
<include
android:id="@+id/xixi"
layout="@layout/support_item"/>
merge标签:
merge标签是作为include标签的一种辅助扩展来使用,它的主要作用是为了防止在引用布局文件时产生多余的布局嵌套。
Android渲染需要消耗时间,布局越复杂,性能就越差。如上述include标签引入了之前的LinearLayout之后导致了界面多了一个层级。
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_title"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="@+id/iv_image"
android:text="这个是MergeLayout,这个是MergeLayout"
android:textSize="12sp" />
</merge>
activity_main就可以直接include了。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/item_merge_layout" />
</RelativeLayout>
viewstub标签:
viewstub是view的子类。他是一个轻量级View, 隐藏的,没有尺寸的View。他可以用来在程序运行时简单的填充布局文件。接着简单试用下viewstub吧。首先修改activity_main.xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_view_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="显示ViewStub"
android:textAllCaps="false"
android:layout_below="@+id/tv_content"/>
<Button
android:id="@+id/btn_view_hide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_toRightOf="@+id/btn_view_show"
android:text="隐藏ViewStub"
android:textAllCaps="false"
android:layout_below="@+id/tv_content"/>
<ViewStub
android:id="@+id/vs_test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout="@layout/item_test_linear_layout"
android:layout_below="@+id/btn_view_show"
android:layout_marginTop="10dp" />
</RelativeLayout>