参考
《Android Apps Proformance Optimization》第九章
概述
在Android程序中,通常会在onCreate()中调用setContentView()加载布局。从onCreate()开始到onResume()结束,99%的时间都耗费在加载布局上,因此优化布局对于提高响应速度很重要。其中有一条很重要的原则:减少所要创建的对象的个数。例如可以延迟某块布局的加载(ViewStub),减少不必要的组件等。
示例
示例一,RelativeLayout:
当布局中要创建的View对象超过10个时,可以用ReleativeLayout来减少个数,提高界面加载速度。
布局如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="str1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="str2"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="str3"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="str4"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</LinearLayout>
上述布局很简单,只是实现一个两行两列的四个TextView。这个布局一共有两个问题:(1)LinearLayout的嵌套,导致
视图层次结构太深;(2)
无用的实例太多,一共在创建7个实例,但有3个是用来定位的。解决起来很简单:用RelativeLayout代替根结点的LinearLayout,这样四个TextView完全可以通过相应的属性进行定位。
示例二,<merge/>:
具体用法可见碎雨(四)。下面说的是一个用法。
由于在加载布局时,系统会在最外面包裹一层FrameLayout。因此,如果布局的根结点是Framelayout,完全可以用<merge>代替。如下:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/img10" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="hello" />
</FrameLayout>
当布局显示到界面上时,会有两层FrameLayout,故可将根结点换成<merge>这样就减少一层FrameLayout。