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

LayoutInflater 與 inflate 用法完全指南

編輯:關於 Android 程式設計

在實際開發中,LayoutInflater 的重要性常被低估。它的角色有點像 findViewById(),但兩者的職責截然不同:LayoutInflater 負責找到 res/layout/ 下的 XML 版面檔並把它「實體化」成 View 物件樹;而 findViewById() 是在已經存在的 View 樹中,依 id 找出具體的 widget(Button、TextView 等)。

什麼時候需要它

  • 畫面尚未載入,或需要動態載入的介面,必須用 LayoutInflater.inflate() 把它讀進來。
  • 已經載入的介面,則直接用 Activity.findViewById() 取得其中的元素即可。

LayoutInflater 是一個抽象類別,宣告方式如下:

public abstract class LayoutInflater extends Object

取得實例的三種寫法

// 1. 由 Activity 取得
LayoutInflater inflater = getLayoutInflater();

// 2. 透過 SystemService
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// 3. 靜態工廠方法
LayoutInflater inflater = LayoutInflater.from(context);

看起來是三種做法,實際上殊途同歸。Activity 的 getLayoutInflater() 會轉呼叫 PhoneWindow 的同名方法:

public PhoneWindow(Context context) {
    super(context);
    mLayoutInflater = LayoutInflater.from(context);
}

而 LayoutInflater.from() 內部是:

public static LayoutInflater from(Context context) {
    LayoutInflater LayoutInflater =
        (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (LayoutInflater == null) {
        throw new AssertionError("LayoutInflater not found.");
    }
    return LayoutInflater;
}

結論很清楚:三種寫法最終都走 Context.getSystemService(),取到的是同一個服務實例。挑自己讀起來順的那一種即可。

inflate 的四種多載

public View inflate(int resource, ViewGroup root)
public View inflate(XmlPullParser parser, ViewGroup root)
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
public View inflate(int resource, ViewGroup root, boolean attachToRoot)

四個版本的回傳值都是 View,差別只在參數來源與是否附加到父容器。

resource 是版面 id;parser 是你要解析的 XML 解析器。

root 的行為最容易搞混,務必記牢:

  • 傳入 null:產生的 View 自己當根節點,此時可以直接對它呼叫 findViewById() 存取內部元件。
  • 傳入非 null:該 View 會被掛到 root 之下,root 成為新的根。

attachToRoot 決定是否真的把新 View 附加到 root:

  • true:解析出來的 XML 直接成為 root 的子節點。
  • false:只回傳 View 物件,root 僅用來提供 LayoutParams 的參照,不會真的掛上去。

這裡有個實務上的細節:即使 attachToRoot 為 false,只要 root 不是 null,inflate 仍會套用 root 的 LayoutParams 產生正確的 LayoutParams 物件。這也是為什麼在 ListView 的 getView 中,我們通常傳 parent 而非 null。

一個常見的崩潰場景

如果你在 Activity 中這樣寫:

setContentView(new MySurfaceView(this));

那麼 findViewById(R.id.xxx) 去取版面檔中的 TextView 時,很可能會拿到 null 並在後續呼叫時拋出空指標例外。原因很直接:此時的根視圖已經是 MySurfaceView,原本的 layout XML 並沒有被載入,那個 TextView 從來就不存在於 View 樹中。

解法是先把版面明確地 inflate 出來:

View view = LayoutInflater.from(this).inflate(R.layout.passover, null);
// 之後就能安全地存取
TextView tv = (TextView) view.findViewById(R.id.xxx);

注意:每次 inflate 都會產生一個全新的物件實例,這點在複用時要留意。

inflate 與 setContentView 的差別

inflate() 只是把 XML 描述的版面「找出來」並實體化,它是隱藏的,不會自己出現在畫面上;setContentView() 則是把版面掛成 Activity 的內容,呼叫後 UI 立刻顯示。

換個比喻:inflate 像是「隱性充氣」——版面被吹成一個有實體、有尺寸的 View 物件,但還停在隱藏狀態;setContentView 才是真正把它擺上舞台。

所以典型流程是:在 Activity 中用 setContentView 顯示主畫面;而在非 Activity 的場合(例如自訂 View、Dialog、Adapter),需要操作某個版面上的元件時,就靠 LayoutInflater 動態載入。

動態載入的完整三步驟

假設有這樣一個版面檔:

<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/tview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="ATAAW.COM">

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="按鈕" />
</TextView>

第一步,取得 LayoutInflater:

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

第二步,呼叫 inflate 載入版面資源:

View view = inflater.inflate(R.layout.example, null);

參數一是要載入的 XML 資源,載入失敗會拋出 InflateException;參數二是新 View 的父層,可以設為 null。

第三步,把新 View 放進需要的位置:

// 先取得目前的容器
ViewGroup myView = (ViewGroup) findViewById(R.id.container);
// 指定 LayoutParams 後加入
myView.addView(view, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));



也可以在呼叫 inflate 時直接把 root 傳進去,一次完成加入:

inflater.inflate(R.layout.login, myView);

但這種寫法比較難控制新 View 的長寬,實務上較建議用前一種。

另一條路:View.inflate()

除了 LayoutInflater,也可以使用 View 的靜態方法:

static View inflate(Context context, int resource, ViewGroup root)

View view = View.inflate(this, R.layout.example, null);

三個參數分別是上下文、版面檔與父容器。同樣地,也可以傳入 myView 直接加入父容器。效果與 LayoutInflater.inflate 一致,只是呼叫形式不同。

R.layout 與 R.id 的分工

這是最常被混用的兩個資源引用:

  • R.layout.xx 指向 res/layout/xx.xml 這個版面檔,透過 inflate 使用。
  • R.id.xx 指向版面檔中某個元件的 id,透過 findViewById 使用。

關鍵限制是:findViewById() 只能找到「目前已經被載入的那棵 View 樹」裡的元件。如果某個元件不在 setContentView 設定的版面中,直接呼叫 activity.findViewById() 就會得到 null。

對話框版面的正確取用方式

假設你要操作一個 dialog_layout.xml,它並不是 Activity 的主版面,就必須先 inflate 再 findViewById:

View view1 = View.inflate(this, R.layout.dialog_layout, null);
TextView dialogTV = (TextView) view1.findViewById(R.id.dialog_tv);
dialogTV.setText("abcd");

這裡的 R.id.dialog_tv 屬於對話框版面,若直接寫成 this.findViewById(R.id.dialog_tv) 一定會出錯。

補充:ViewStub 的 inflate

還有一個容易混淆的同名方法。ViewStub 是 Android 提供的輕量佔位元件,平時幾乎不佔資源,等到需要時才把真正的版面填進來:

View viewStub = ((ViewStub) findViewById(R.id.stubView)).inflate();

它回傳的是被載入的 View 本身,適合用於「首次顯示才需要」的區塊,例如錯誤提示頁、空資料狀態頁。與 LayoutInflater 的 inflate 相比,ViewStub 的優勢是延後載入,能有效降低啟動時的版面解析成本。

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