Android_布局优化

原则

  • 尽量多使用LinearLayout和RelativeLayout。在布局层次一样的情况下,建议用LinearLayout,因为LinearLayout性能要高一些。但是用LinearLayout有时会使嵌套层次变多,这样的情况应该用RelativeLayout。
  • 尽量用include标签来抽取可复用的布局
  • 尽量用ViewStub标签来加载不常用的布局
  • 尽量用merge标签来减少层次

RelativeLayout代替LinearLayout简化层次

比如我们要画出下面的布局:

如果用LinearLayout的话会这样写:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView  android:layout_width="40dp" android:layout_height="40dp" android:background="#ff0099cc" />

    <LinearLayout  android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:orientation="vertical">

        <TextView  android:layout_width="match_parent" android:layout_height="20dp" android:background="#ff669900" />

        <TextView  android:layout_width="match_parent" android:layout_height="20dp" android:background="#ffff8800" />

    </LinearLayout>
</LinearLayout>

但是可以用RelativeLayout来减少层次:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView  android:id="@+id/text_a" android:layout_width="40dp" android:layout_height="40dp" android:background="#ff0099cc" />

    <TextView  android:id="@+id/text_b" android:layout_width="match_parent" android:layout_height="20dp" android:layout_toRightOf="@id/text_a" android:layout_toEndOf="@id/text_a" android:background="#ff669900" />

    <TextView  android:layout_below="@id/text_b" android:layout_width="match_parent" android:layout_height="20dp" android:layout_toRightOf="@id/text_a" android:layout_toEndOf="@id/text_a" android:background="#ffff8800" />

</RelativeLayout>

< include />

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">

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

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

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

</LinearLayout>

< merge />

merge标签有以下两种用法:

  1. FrameLaout作为根节点的时候,可以用merge替换。android系统在加载layout的时候会自动在外层加一个FrameLayout,这样就多嵌套了一层FrameLayout,用merge的话,就只存在一个FrameLayout。
  2. 使用include标签是,和外层布局一样。例如,一个垂直布局的layout a通过include引入了一个垂直布局的layout b,因为都是垂直布局,所以存在了不必要的LinearLayout嵌套。如果使用merge,就会避免嵌套。

< ViewStub />

ViewStub的好处就是用的时候才加载,不用就不加载。如下:

<ViewStub  android:id="@+id/stub_import" android:inflatedId="@+id/panel_import" android:layout="@layout/progress_overlay" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" />

加载的时候可以用以下两种方法的一种:

((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();

你可能感兴趣的:(android)