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

Android 抽象佈局:include、merge 與 ViewStub 的用法

編輯:關於 Android 程式設計

在佈局優化上,Android 官方特別推薦了 include、merge、ViewStub 這三種標籤,各自解決不同的問題。下面逐一說明它們的優勢與使用方式。

一、佈局重用: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>

使用要點:

  1. layout 屬性是唯一必填,用於指定要引入的佈局。
  2. 可搭配其他屬性;若 include 指定了 id,會覆蓋被引入佈局原本的 id。
  3. 所有 android:layout_* 屬性都有效,但必須同時寫上 layout_width 與 layout_height。
  4. 可包含兩個相同的 include,透過各自 id 再往下 findViewById 來區分取得。

二、精簡層級:merge

merge 標籤在優化 UI 結構時非常關鍵,它能刪減多餘的層級。當你的父佈局與被引入佈局方向一致時,被引入的 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>

當你以 include 引入這份佈局時,系統會忽略 merge 節點,直接把兩個 Button 加入父容器。

三、按需加載:ViewStub

ViewStub 最大的優勢是「用到才加載」,不影響初始化時的效能,特別適合進度條、錯誤提示等不常用到的佈局。它是一個不可見、大小為 0 的 View:

<ViewStub android:id="@+id/stub_import"
    android:inflatedId="@+id/panel_import"
    android:layout="@layout/progress_overlay"
    android:layout_gravity="bottom"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" />

想加載時,可用以下任一方式:

((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// 或
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();

調用 inflate() 後,ViewStub 會被引用資源取代並回傳該 view,省去再次 findViewById 的麻煩。

最後提醒:ViewStub 目前仍不支援在自身內部使用 merge 標籤。

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