当你在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" />