Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

巧用 include 與 merge 標籤重複使用 Android 佈局

編輯:Android 開發實例

雖然 Android 提供了各式各樣的元件來拼湊小而可重複使用的互動元素,但當畫面需要整塊重複使用某個大型元件時,就需要更完整的佈局複用手段。透過 <include/> 與 <merge/> 這兩個標籤,你可以把一個佈局嵌入到另一個佈局之中,讓自訂的 UI 元件更容易被到處引用。

佈局複用的威力在於,你能把「是/否」按鈕面板、帶說明文字的自訂進度條這類複雜結構,抽離成獨立檔案集中管理,再插入到各個畫面裡,大幅降低重複維護的成本。

建立可複用的佈局

一旦確認某個佈局需要重複使用,就替它建立一個新的 XML 檔案。以下是一段來自 G-Kenya 專案、用來定義標題欄的佈局,它可以被插入到每個 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/> 中覆寫被引入佈局的所有版面參數(即 android:layout_* 屬性):

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

不過要留意:若你打算覆寫佈局屬性,就必須同時覆寫 android:layout_height 與 android:layout_width,否則其他屬性將無法生效。

使用 <merge/> 標籤

<merge/> 標籤的用途,是排除「把一個佈局插入到另一個佈局時」所多產生的冗餘 View Group。舉例來說,假設你的可複用佈局是一個包含兩個子視圖的垂直 LinearLayout,當它被嵌入另一個同樣是垂直的 LinearLayout 時,結果就會變成「垂直 LinearLayout 裡又包了一層垂直 LinearLayout」。這種多餘的巢狀結構毫無意義,還會拖慢 UI 效能。

為了避免這類冗餘,你可以把 <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 所在的位置,省下一層無用的容器。

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