閱讀803 返回首頁    go 阿裏雲 go 技術社區[雲棲]


提高顯示布局文件的性能 2 - 使用include標簽重用Layout

Re-using Layouts with <include/>

盡管Android提供了很多種小的組件可以重用,我們還需要自定義一些稍微複雜一點的小組件進行重用。我們可以使用<include/> and <merge/> 標簽來對當前的layout嵌入一些其他的layout.
在創建一個稍微複雜一點的layout時,重用layout是個很給力的方法。比如我們需要一個YES/NO的控製欄,包含文字提示的Progress bar。這意味著我們可以在很多地方重用那些自定義的layout.

Create a Re-usable Layout [創建一個可重用的Layout]

如果你已經知道哪些組件是會重用的,我們可以創建一個XML並且定義這個layout。
例如:下麵定義了一個需要在每個Activity都需要顯示的titlebar.xml
  1. <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"  
  2.     android:layout_width=”match_parent”  
  3.     android:layout_height="wrap_content"  
  4.     android:background="@color/titlebar_bg">  
  5.   
  6.     <ImageView android:layout_width="wrap_content"  
  7.                android:layout_height="wrap_content"   
  8.                android:src="@drawable/gafricalogo" />  
  9. </FrameLayout>  

Use the <include> Tag [使用<include>標簽]

下麵示例了一個包含了titlebar控件的布局:
  1. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"  
  2.     android:orientation="vertical"   
  3.     android:layout_width=”match_parent”  
  4.     android:layout_height=”match_parent”  
  5.     android:background="@color/app_bg"  
  6.     android:gravity="center_horizontal">  
  7.   
  8.     <include layout="@layout/titlebar"/>  
  9.   
  10.     <TextView android:layout_width=”match_parent”  
  11.               android:layout_height="wrap_content"  
  12.               android:text="@string/hello"  
  13.               android:padding="10dp" />  
  14.   
  15.     ...  
  16.   
  17. </LinearLayout>  
我們可以重寫任何include裏麵的屬性,例如:
  1. <include android:id=”@+id/news_title”  
  2.          android:layout_width=”match_parent”  
  3.          android:layout_height=”match_parent”  
  4.          layout=”@layout/title”/>  

Use the <merge> Tag [使用<merge>標簽]

某些時候,自定義可重用的布局包含了過多的層級標簽,比如我們需要在LinearLayout裏麵嵌入一個重用的組件,而恰恰這個自定義的可重用的組件根節點也是LinearLayout,這樣就多了一層沒有用的嵌套,無疑這樣隻會拖慢程序速度。而這個時候如果我們使用merge根標簽就可以避免那樣的問題。
例如:
  1. <merge xmlns:android="https://schemas.android.com/apk/res/android">  
  2.   
  3.     <Button  
  4.         android:layout_width="fill_parent"   
  5.         android:layout_height="wrap_content"  
  6.         android:text="@string/add"/>  
  7.   
  8.     <Button  
  9.         android:layout_width="fill_parent"   
  10.         android:layout_height="wrap_content"  
  11.         android:text="@string/delete"/>  
  12.   
  13. </merge>  
這樣的話,使用<include>包含上麵的布局的時候,係統會自動忽略merge層級,而把兩個button直接放置與include平級。

最後更新:2017-04-04 07:03:06

  上一篇:go 中國網民在裸奔
  下一篇:go 為什麼80後集體缺席互聯網