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

Android 佈局優化:include、merge 與 ViewStub

編輯:關於 Android 程式設計

Android 官方在佈局優化中提到三個常用標籤:include、merge 與 ViewStub。它們分別負責重用佈局、減少多餘層級,以及延後載入不常用元件。以下說明各自的使用方式與適用情境。

include:重用佈局

include 可把另一個 XML 佈局嵌入目前畫面,適合處理重複的標題列、列表項或頁尾。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

</LinearLayout>

使用 include 時,layout_width 與 layout_height 是必要的;若 include 指定 id,會覆蓋被引入佈局根節點原本的 id。宣告多個相同 include 時,可利用不同 id 再分別 findViewById。

merge:減少多餘層級

merge 的作用是把子節點直接合併到父容器,而不額外建立一層 ViewGroup。它常用來取代 FrameLayout,或在 include 時避免重複包一層 LinearLayout。

<merge xmlns:android="https://schemas.android.com/apk/res/android">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="新增" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="刪除" />
</merge>

當系統加入這個 merge 佈局時,會忽略 merge 節點本身,直接把兩個 Button 放進父容器,从而降低檢視層級。

ViewStub:需要時才載入

ViewStub 是一個不可見且不佔用空間的佔位元件。適合放在不常用但可能需要顯示的區塊,例如錯誤提示、載入中遮罩或進度條。

<ViewStub
    android:id="@+id/stub_import"
    android:inflatedId="@+id/panel_stub"
    android:layout="@layout/progress_overlay"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

真正需要顯示時,可以設定可見性或直接 inflate:

ViewStub stub = findViewById(R.id.stub_import);
stub.setVisibility(View.VISIBLE);
View panel = stub.inflate();

使用 ViewStub 的重點是延後載入,避免初始化時就解析所有不常用佈局。它能有效降低初始渲染成本,但要注意它與 merge 的搭配會受到平台版本與使用情境影響,實作前應先驗證。

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