當你在Application中創建複雜的佈局時,頁面的渲染過程也變得更加緩慢。
此時,我們需要利用 <include />標籤(避免重複渲染)和 ViewStub類(延遲加載)來優化我們的頁面。
一、利用<include />標籤來避免重複渲染
當我們需要爲App中的每個View都添加一個header或者footer時,你會怎麼做?
重複地複製粘貼可以解決這個問題,但未免太繁雜。可以試着使用<include />標籤:
第一種方式,在<include />標籤內指定width及height:
main.xml
-
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
-
android:layout_width= "fill_parent"
-
android:layout_height= "fill_parent" >
-
-
<Button
-
android:layout_width ="fill_parent"
-
android:layout_height ="wrap_content"
-
android:layout_gravity ="center_vertical"
-
android:onClick ="onShowMap"
-
android:text ="@string/show_map" />
-
-
<include
-
android:layout_width ="fill_parent"
-
android:layout_height ="wrap_content"
-
android:layout_alignParentBottom ="true"
-
android:layout_marginBottom ="30dp"
-
layout ="@layout/footer" />
-
-
</RelativeLayout>
footer.xml
-
<TextView xmlns:android = "http://schemas.android.com/apk/res/android"
-
android:layout_width= "0dp"
-
android:layout_height= "0dp"
-
android:gravity= "center"
-
android:text= "@string/footer_text" />
有個小細節需要注意,在footer.xml中,我們將width及height都設爲0dp.目的是爲了配合<include/>標籤中對width及height的定義。
第二種方式,直接引用:
main.xml
-
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
-
android:layout_width= "fill_parent"
-
android:layout_height= "fill_parent" >
-
-
<Button
-
android:layout_width ="fill_parent"
-
android:layout_height ="wrap_content"
-
android:layout_gravity ="center_vertical"
-
android:onClick ="onShowMap"
-
android:text ="@string/show_map" />
-
-
<include layout ="@layout/footer" />
-
-
</RelativeLayout>
footer.xml
-
<TextView xmlns:android = "http://schemas.android.com/apk/res/android"
-
android:layout_width= "fill_parent"
-
android:layout_height= "wrap_content"
-
android:layout_alignParentBottom= "true"
-
android:layout_marginBottom= "30dp"
-
android:gravity= "center"
-
android:text= "@string/footer_text" />