儘管Android提供了各種各樣的控件來支持控件級的重用,但是您可能有特別的佈局需要重用。您可以通過 <include/> 標籤來重用整個佈局;使用 <merge/> 標籤在當前佈局中引入其他佈局。
佈局重用功能讓您可以重用複雜的佈局,該功能是非常好用的。例如,一個 帶有 確定、取消 兩個按鈕的佈局;或者帶有描述文字的自定義進度條。這就意味着,在您的程序中那些出現在各個佈局文件中的一樣的代碼可以單獨的提取出來,放到一個獨立的佈局文件中,然後其他的佈局引用這個文件即可。 可Java中的函數重構一樣,把相同的代碼重構爲一個函數,其他代碼調用這個函數即可。通過繼承 View 可以創建自定義控件,而通過重用佈局文件更加簡化了這個過程。
創建可重用的佈局
如果您已經設計好了需要重用的佈局,只有創建一個佈局XML文件即可。例如,這裏是一個來自於 G-Kenya codelab 的佈局文件,定義了在每個Activity中都要使用的一個自定義標題 (titlebar.xml):
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width=”match_parent” android:layout_height="wrap_content" android:background="@color/titlebar_bg"> <ImageViewandroid:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gafricalogo"/> </FrameLayout>
佈局中的根 View 應該就是您希望添加到目標佈局中的控件。
使用 <include> 標籤
在您希望添加可重用佈局的文件中,使用 <include/> 標籤引入重用的佈局。例如,這裏是 G-Kenya codelab 中引用上面定義的標題佈局的代碼:
<LinearLayoutxmlns: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"> <strong><includelayout="@layout/titlebar"/></strong> <TextViewandroid:layout_width=”match_parent” android:layout_height="wrap_content" android:text="@string/hello" android:padding="10dp"/> ... </LinearLayout>
您還可以在 <include/>標籤裏面重新定義佈局參數 (所有 android:layout_* 參數) ,例如:
<includeandroid:id=”@+id/news_title” android:layout_width=”match_parent” android:layout_height=”match_parent” layout=”@layout/title”/>
使用 <merge> 標籤
<merge /> 標籤幫助你消除不必要的View group。 例如 ,如果您的主佈局是一個垂直方向的LinearLayout,而裏面引用了另外一個可重用的佈局,該佈局同樣是垂直方向的 LinearLayout 爲根佈局,這樣的話最終的佈局裏面會有兩個垂直方向的 LinearLayout, 而引用的那個LinearLayout 是多餘的。
爲了避免這種多餘的View Group出現,您可以使用 <merge> 標籤做爲可重用佈局的根標籤。 如下所示:
<mergexmlns: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> 標籤,然後把那兩個按鈕直接放到 <include/> 標籤的位置。