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

View 繪製優化:用 include 與 merge 標籤復用佈局檔

編輯:關於 Android 程式設計

Android 內建了大量可重複使用的小型互動元件,但真實專案裡往往更需要復用「較大的片段」——整塊佈局檔。要有效率地做到這件事,關鍵是 <include /> 與 <merge /> 這兩個標籤。

為什麼要復用佈局檔

把佈局抽出來獨立管理,能帶來兩個好處:一是像「Yes / No 兩個按鈕的確認面板」或「帶文字說明的進度條」這種元件,可以隨處重複使用;二是讓複雜畫面中的每個區塊各自獨立,需要時再組裝起來。搭配自訂 View 時,這種做法尤其省事。

步驟一:建立可復用的佈局檔

先想清楚這個元件長什麼樣子,然後建立對應的 xml。以下是一個自訂標題欄 titlebar.xml:

<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>

由於這份佈局會被嵌進其他佈局中,它的根檢視(root View)最好能精確對應實際使用情境。

步驟二:用 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 /> 節點上直接覆寫被引入佈局的根檢視屬性——凡是 android:layout_ 開頭的屬性都可以覆寫。不過要注意:覆寫生效的前提是被引入佈局的根檢視本身有明確的 layout 寬高設定。

步驟三:用 merge 消除多餘的巢狀層級

當被復用的佈局需要「兩個以上的子檢視」時,它必須有一個根檢視,否則編譯器會報錯。但如果你為了合規硬加一層 LinearLayout,就會變成「垂直 LinearLayout 裡再嵌一個垂直 LinearLayout」——多這一層毫無功能價值,只會拖慢 UI 效能。

原本的寫法:

<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="horizontal">

    <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" />
</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 的位置。

兩個標籤怎麼選

判斷很簡單:被復用的片段只有單一根檢視(像一個 FrameLayout 包一張圖),用 include 即可;片段由多個並列子檢視組成、且不希望多一層容器,就用 merge。兩者常搭配使用,也是 View 繪製優化裡最不需要改動邏輯、就能削減檢視樹深度的一招。搭配 Layout 或 Hierarchy Viewer 觀察層級變化,效果會很直觀。

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