儘管Android提供了各種組件來實現小而可複用的互動元素,你也可能因為布局需要複用一個大組件。為了高效複用完整布局,你可以使用<include/>和<merge/>標籤嵌入另一個布局到當前布局。所以當你通過寫一個自訂視圖建立獨立UI組件,你可以放到一個布局檔案裡,這樣更容易複用。
複用布局因為其允許你建立可複用的複雜布局而顯得非常強大。如,一個 是/否 按鈕面板,或帶描述文本的自訂進度條。這同樣意味著,應用裡多個布局裡共同的元素可以被提取出來,獨立管理,然後插入到每個布局裡。
建立可複用布局
如果你已經知道哪個布局需要重用,就建立一個新的xml檔案來定義布局。如,下面是一個來自G-Kenya程式碼程式庫裡定義標題列的布局,它可以被插到每個Activity裡:
複製代碼 代碼如下:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width=”match_parent”
android:layout_height="wrap_content"
android:background="@color/titlebar_bg">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/gafricalogo" />
</FrameLayout>
根視圖應該剛好和你在其他要插入這個視圖的視圖裡相應位置一樣。
使用<include/>標籤
在你要添加可複用布局的布局裡,添加<include/>標籤。下面是添加標題列:
複製代碼 代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background="@color/app_bg"
android:gravity="center_horizontal">
<include layout="@layout/titlebar"/>
<TextView android:layout_width=”match_parent”
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />
...
</LinearLayout>
你同樣可以覆蓋所有的布局參數(android:layout_*屬性)
複製代碼 代碼如下:
<include android:id=”@+id/news_title”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
layout=”@layout/title”/>
可是,如果你要用include標籤覆蓋布局屬性,為了讓其他屬性生效,就必須覆蓋android:layout_height和android:layout_width。
使用<merge/>標籤
<merge/>標籤協助你排除把一個布局插入到另一個布局時產生的多餘的View Group.如,你的被複用布局是一個垂直的線性布局,包含兩個子視圖,當它作為一個被複用的元素被插入到另一個垂直的線性布局時,結果就是一個垂直的LinearLayout裡包含一個垂直的LinearLayout。這個嵌套的布局並沒有實際意義,而且會讓UI效能變差。
為了避免插入類似冗餘的View Group,你可以使用<merge/>標籤標籤作為可複用布局的根節點,如:
複製代碼 代碼如下:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/add"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/delete"/>
</merge>
現在,當你使用include標籤插入這個布局到另一個布局時,系統會忽略merge標籤,直接把兩個Button替換到include標籤的位置。