透過 <includegt; 重複使用版面配置

雖然 Android 提供多種小工具,讓您享有可重複使用的小型互動元素,但您可能仍須重複使用需要特殊版面配置的大型元件。為了有效率地重複使用完整版面配置,請使用 <include><merge> 標記將版面配置嵌入另一個版面配置中。

這可讓您建立複雜的版面配置,例如「是」或「否」按鈕面板,或含有說明文字的自訂進度列。也就是說,您可以擷取多個版面配置中通用的應用程式元素、分別管理,然後加入每個版面配置中。雖然您可以編寫自訂的 View 建立個別 UI 元件,但只要重複使用版面配置檔案就能更輕鬆地達成這個目的。

建立可重複使用的版面配置

請先建立新的 XML 檔案,然後定義您希望重複使用的版面配置。舉例來說,以下版面配置可定義要加入每個活動的標題列 (titlebar.xml):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg"
    tools:showIn="@layout/activity_main" >

    <ImageView android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/gafricalogo" />
</FrameLayout>

根層級 View 必須與您打算新增此版面配置的每個版面配置中的顯示方式完全相同。

使用 <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> 標記中指定這些參數即可。例如:

<include android:id="@+id/news_title"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         layout="@layout/title"/>

不過,如要使用 <include> 標記覆寫版面配置屬性,請一併覆寫 android:layout_heightandroid:layout_width,讓其他版面配置屬性生效。

使用 <merge> 標記

在某個版面配置中加入其他版面配置時,<merge> 標記可協助減少檢視區塊階層中多餘的檢視區塊群組。<merge> 的其中一個用途是擴充 ViewGroup 以實作自訂檢視區塊。

舉例來說,如果您的主要版面配置是直向 LinearLayout,當中有兩個連續的檢視畫面可重複使用於多個版面配置,那麼您加入兩個檢視畫面的可重複使用的版面配置就需要根層級檢視畫面。不過,如果使用其他 LinearLayout 做為可重複使用的版面配置的根層級,會導致顯示在直向 LinearLayout 中的直向 LinearLayout。巢狀 LinearLayout 沒有實際用途,還會降低 UI 效能。

不過,您可以擴充 LinearLayout 來建立自訂檢視畫面,並使用版面配置 XML 描述其子檢視畫面。XML 中的頂端標記是 <merge>,而非 LinearLayout,如以下範例所示:

<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> 元素並直接將兩個按鈕加入版面配置中,藉此取代 <include> 標記。

如要進一步瞭解 <include>,請參閱「版面配置資源」。