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

Android 官方培訓課程中文版:布局性能優化之重用佈局(include 與 merge)

編輯:關於 Android 程式設計

即使 Android 內建了豐富的常用控件,實務上仍常遇到需要重用較複雜佈局的情況。此時可以善用 <include/> 與 <merge/> 兩個標籤,把一段佈局嵌入到另一段佈局之中。

可重用佈局這項能力非常實用:你可以把「確定/取消」按鈕列、或「進度條 + 文字說明」這類組合抽成獨立檔案,各處重複引用,並對它們進行統一維護。相比撰寫自訂 View,這種做法門檻更低、也更直覺。

建立一個可重用的佈局

先決定哪一段畫面需要重用,然後建立一個新的 XML 檔案來定義它。以下定義一個 ActionBar 樣式的標題列,因為它會出現在每個 Activity 中:

<FrameLayout
    android:background="@color/titlebar_bg"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

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

</FrameLayout>

使用 include 標籤

在希望插入重用佈局的位置加上 <include/> 即可:

<LinearLayout
    android:background="@color/app_bg"
    android:gravity="center_horizontal"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <include layout="@layout/titlebar" />

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:text="@string/hello" />

</LinearLayout>

你也可以覆寫被引入佈局的參數,但只限於以 android:layout_* 開頭的屬性:

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

需要注意的是,若想覆寫 <include> 的佈局屬性,必須同時覆寫 android:layout_height 與 android:layout_width,否則其他屬性不會生效。

使用 merge 標籤

<merge> 的作用是在嵌入佈局時消除多餘的 View 容器。

舉例來說,主佈局是一個垂直的 LinearLayout,裡面有兩個需要在多處重用的 View。這兩個 View 若獨立成檔案,就必須有一個根節點。如果選用 LinearLayout 當根節點,結果會變成「垂直 LinearLayout 裡又嵌一個垂直 LinearLayout」——這層嵌套並非必要,還會額外增加測量與配置成本,拖慢畫面效能。

為避免這種冗餘容器,改用 <merge> 作為根節點:

<merge xmlns:android="https://schemas.android.com/apk/res/android">
    <Button
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="@string/add" />
    <Button
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="@string/delete" />
</merge>

這樣一來,系統在引入時會自動略過 <merge> 標籤,直接把兩個 Button 掛到 <include/> 所指定的位置,佈局層級維持扁平,效能自然更好。

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