透過 重複使用版面配置

雖然 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 應該要以您預期的方式顯示。

注意:上方 XML 中的 tools:showIn 是一種特殊屬性,會在編譯期間移除,且只會在 Android Studio 中用於設計作業。這項屬性會指定要「加入」這個檔案的版面配置,方便您預覽這個檔案嵌入上層版面配置的顯示效果,並視需要進行編輯。

使用 <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> 標記可協助減少檢視區塊階層中多餘的檢視區塊群組。舉例來說,假設您的主要版面配置是直向 LinearLayout,當中有兩個連續的檢視畫面可重複使用於多個版面配置,那麼您加入兩個檢視畫面的可重複使用的版面配置就需要根層級檢視畫面。不過,如果使用其他 LinearLayout 做為可重複使用的版面配置的根層級,將產生顯示在直向 LinearLayout 中的直向 LinearLayout。巢狀 LinearLayout 只會降低 UI 效能。

為避免加入這類多餘的檢視區塊群組,建議您改為使用 <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> 元素並直接將兩個按鈕加入版面配置中,藉此取代 <include> 標記。

如要進一步瞭解這個主題,請參閱「版面配置資源」一文。