Android性能优化之:布局优化

布局优化的思想很简单,就是尽量减少布文件的层级,这样Android绘制时的工作量就少了,程序性能也随之提高。

一、删除无用的控件和层级,有选择性地使用性能较高的ViewGroup

如果RelativeLayout和LinearLayout都能实现的布局,应优先使用LinearLayout,因为RelativeLayout的功能比较复杂,布局过程话费更多的CPU时间。
FrameLayout也是和LinearLayout一样高效。
但是,如果是在要通过LinearLayout嵌套或者FrameLayout嵌套实现的布局, 用RelativeLayout也可实现的情况下,还是用回RelativeLayout更好,因为ViewGroup的嵌套相当于增加了布局的层
级,降低了程序性能。

二、使用<include>标签、<merge>标签和ViewStub

<inlucde>标签:
通过<include>标签可以加载指定的布局,可实现布局的重用。
<include
        layout="@layout/temp_layout"/>
通过layout=“@layout/temp_layout"指定了要加载的布局。
<include>标签只支持android:layout_开头的属性,比如android:layout_width、android:layout_height,其他属性不支持,当然,android:id 就除外了。
如果指定的布局文件的根元素定义了id属性,<include>标签也制定了id属性,则以<include>指定的标签为准。
注意,如果<include> 指定了android_layout_开头的属性,必须要存在android:layout_width和android:layout_height,否则会无效。

<merge>标签:
<merge>标签一般和<include>标签一起使用来减少布局的层级。
如果当前布局是竖直方向的LinearLayout,用<include>标签包含的布局也是用了竖直方向的LinearLayout,那么,则可用将被包含的布局的LinearLayout换成<merge>标签。
通过使用<merge>标签,可以去掉多余的那一层LinearLayout。如下代码:
temp_layout.xml:
       
<?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">
    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#000000"/>
    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#00ffff"/>
</merge>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <View
        android:layout_height="50dp"
        android:layout_width="fill_parent"
        android:background="#00ffff"/>
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <include
        layout="@layout/temp_layout"/>
</LinearLayout>

ViewStub:
ViewStub继承了View,它是轻量级的,而且高和宽都是0,因此它是不参与任何布局和绘制的过程。
<ViewStub
        android:id="@+id/stub"
        android:inflatedId="@+id/flated_layout"
        android:layout="@layout/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

stub是ViewStub的id,show是flated_layout这个布局的根元素的id。可通过下面两种办法来加载:

((ViewStub)findViewById(R.id.stub)).setVisibility(View.VISIBLE);
或者
View importPannel = ((ViewStub) findViewById(R.id.stub)).inflate();

当ViewStub通过setVisibility或者inflate方法加载以后,ViewStub就会被它内部的布局替换掉,ViewStub就不在是整个布局结构中的一部分了。另外,目前ViewStub还不支持<merge>标签。


猜你喜欢

转载自blog.csdn.net/u014686721/article/details/51956316