利用標籤來避免重複渲染

當你在Application中創建複雜的佈局時,頁面的渲染過程也變得更加緩慢。
此時,我們需要利用 <include />標籤(避免重複渲染)和 ViewStub類(延遲加載)來優化我們的頁面。
一、利用<include />標籤來避免重複渲染

當我們需要爲App中的每個View都添加一個header或者footer時,你會怎麼做?
重複地複製粘貼可以解決這個問題,但未免太繁雜。可以試着使用<include />標籤:

第一種方式,在<include />標籤內指定width及height:
main.xml
[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"  
  2.     android:layout_width"fill_parent"  
  3.     android:layout_height"fill_parent" >  
  4.   
  5.     <Button  
  6.         android:layout_width ="fill_parent"  
  7.         android:layout_height ="wrap_content"  
  8.         android:layout_gravity ="center_vertical"  
  9.         android:onClick ="onShowMap"  
  10.         android:text ="@string/show_map" />  
  11.   
  12.     <include  
  13.         android:layout_width ="fill_parent"  
  14.         android:layout_height ="wrap_content"  
  15.         android:layout_alignParentBottom ="true"  
  16.         android:layout_marginBottom ="30dp"  
  17.         layout ="@layout/footer" />  
  18.   
  19. </RelativeLayout>  

footer.xml
[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <TextView xmlns:android = "http://schemas.android.com/apk/res/android"  
  2.     android:layout_width"0dp"  
  3.     android:layout_height"0dp"  
  4.     android:gravity"center"  
  5.     android:text"@string/footer_text" />  

有個小細節需要注意,在footer.xml中,我們將width及height都設爲0dp.目的是爲了配合<include/>標籤中對width及height的定義

第二種方式,直接引用:
main.xml
[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"  
  2.     android:layout_width"fill_parent"  
  3.     android:layout_height"fill_parent" >  
  4.   
  5.     <Button  
  6.         android:layout_width ="fill_parent"  
  7.         android:layout_height ="wrap_content"  
  8.         android:layout_gravity ="center_vertical"  
  9.         android:onClick ="onShowMap"  
  10.         android:text ="@string/show_map" />  
  11.   
  12.     <include layout ="@layout/footer" />  
  13.   
  14. </RelativeLayout>  

footer.xml
[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <TextView xmlns:android = "http://schemas.android.com/apk/res/android"  
  2.     android:layout_width"fill_parent"  
  3.     android:layout_height"wrap_content"  
  4.     android:layout_alignParentBottom"true"  
  5.     android:layout_marginBottom"30dp"  
  6.     android:gravity"center"  
  7.     android:text"@string/footer_text" />  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章