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

Android 性能優化(佈局篇):用 include 與 merge 複用佈局

編輯:關於 Android 程式設計

接下來一段時間,我會持續翻譯並整理 Android 官方關於效能提升的文件。這是佈局篇的另一主題:透過標籤複用佈局。

題外話:實務上常常會用到高度相似的佈局片段。既然一樣,不妨把它整段抽出來獨立成一個檔案,一方面避免在多個檔案中重複書寫,另一方面日後要改也只需改一處。

為什麼要複用佈局

Android 提供了豐富控件方便互動,但你多少還是會需要重複使用某些大型元件組合。與其在每個佈局檔裡重寫一次,不如用 <include> 與 <merge> 讓一個佈局出現在另一個佈局中。

複用佈局在這種情況下特別有用:它讓你能建立複雜但可重複使用的元件,例如一組 yes/no 按鈕、一個帶文字的自定義進度條。這也意味著 App 中某些元素是通用的,你可以為它們建立自定義 View,讓複用更靈活。

建立可複用的佈局

如果你已經知道哪些佈局要反覆使用,就為它們建立一個新的佈局檔。以下來自 G-Kenya 程式碼實驗室的例子,定義了一個會被每個 Activity 引用的標題欄:

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

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

這個 View 應該與你希望它在各 Activity 中的呈現效果一致,這樣才能被安心複用。

使用 <include> 標籤

要把可複用元件加入另一個佈局,用 <include>。以下同樣來自 G-Kenya 的例子,用來引入上面那個標題欄:

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

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

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

你也可以在 <include> 標籤上覆寫被引入佈局的屬性,例如 android:layout_* 這類參數:

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

但要注意:若想覆寫佈局屬性,必須同時覆寫 layout_height 與 layout_width,其他屬性才會生效。這是 Android 的規則——include 上的其他屬性只有在明確指定寬高時才會被套用。

使用 <merge> 標籤

<merge> 能有效降低佈局層級。舉例來說,你的佈局是一個垂直 LinearLayout,而想複用的佈局也是垂直 LinearLayout——那麼以另一個 LinearLayout 作為複用佈局的根元素,就會產生「垂直 LinearLayout 包著另一個垂直 LinearLayout」的結果。這種同類型的嵌套毫無意義,還會拖慢 UI 效能。

要避免這種情況,可以在複用佈局中改用 <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>

這樣一來,當你用 <include> 複用它時,系統會忽略 <merge> 標籤本身,直接把兩個 Button 放到 include 所在的位置,父容器的層級因此少了一層。

簡單記法:<include> 負責「把別人的佈局搬過來」,<merge> 負責「搬過來時不要多包一層」。兩者搭配使用,既能消除重複程式碼,又不會付出額外層級的效能代價。

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