Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 使用 include 與 merge 標籤重用版面配置

編輯:關於 Android 程式設計

Android 提供了各種元件來實作小而可重複使用的互動元素,但當版面需要複用一整塊較大的元件時,該怎麼辦?為了有效率地重用完整版面,你可以使用 <include/> 與 <merge/> 這兩個標籤,把另一份版面嵌入目前的版面檔。

這個機制讓「自訂檢視」的價值被放大:把獨立的 UI 元件寫成一個版面檔,之後任何 Activity 都能直接嵌入,而不必複製貼上。

建立可重用的版面

先建立一個新的 XML 檔定義要重用的部分。以下示範一個標題欄版面,可被插入到每個 Activity:

<FrameLayout xmlns:android="https://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="https://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>

include 也可以覆寫被引入版面的所有 layout_* 參數,例如重新指定 id 與尺寸:

<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 時,結果就是「垂直 LinearLayout 裡包一個垂直 LinearLayout」。這層嵌套沒有實際意義,還會讓版面層級變深、拖慢測量與配置效能。

要避免這種冗餘,把可重用版面的根節點改成 <merge>:

<merge xmlns:android="https://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 出現的位置。

兩個標籤的差別

include 負責「把 A 版面放進 B 版面」,merge 負責「去掉多餘的容器」。兩者常搭配使用:merge 當根節點、include 來引入。要留意 merge 不能單獨使用,它必須伴隨 include 才有意義,因為它本身不會產生任何檢視;此外 merge 也無法透過 include 覆寫自身的 layout 參數,因為那些參數會被套用到父容器上。適度使用這兩個標籤,能有效壓淺版面層級,對 ListView 這類需要大量重複繪製的畫面改善明顯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved