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

深度解析 Android LayoutInflater:三個參數的真相與源碼剖析

編輯:關於 Android 程式設計

對於做 Android 開發的人來說,LayoutInflater 並不陌生,尤其在 ListView 的 Adapter 的 getView 方法中幾乎必然出現。但對於 inflate 方法的三個參數 (int resource, ViewGroup root, boolean attachToRoot),很多人的理解其實是錯誤的。本文將通過實踐、源碼與視圖測量三個層次,徹底講清這三個參數的奧妙。

一、一個常見的誤解

初學時,很多人會這麼認為:

  • inflate(layoutId, null):layoutId 最外層控件的寬高會失效;
  • inflate(layoutId, root, false):效果和上面一樣;
  • inflate(layoutId, root, true):這時最外層控件的寬高才能正常顯示。

如果你也這麼想,那就一定要讀完這篇文章——因為這個理解是錯誤的。

二、用實踐檢驗真理

我們寫一個最常見的例子:一個 ListView,每個 Item 裡放一個 120dp×120dp 的按鈕,分別用三種方式加載,觀察差異。

Activity 布局:

<ListView android:id="@+id/id_listview" android:layout_height="wrap_content"
    android:layout_width="fill_parent" xmlns:android="https://schemas.android.com/apk/res/android" />

Item 布局:

<Button android:id="@+id/id_btn" android:layout_height="120dp"
    android:layout_width="120dp" xmlns:android="https://schemas.android.com/apk/res/android" />

關鍵在於 getView 裡那一行 inflate,我們依次嘗試三種寫法:

// 寫法一
convertView = mInflater.inflate(R.layout.item, null);
// 寫法二
convertView = mInflater.inflate(R.layout.item, parent, false);
// 寫法三
convertView = mInflater.inflate(R.layout.item, parent, true);

運行結果如下:

圖一(寫法一):

圖二(寫法二):

圖三(寫法三):直接崩潰報錯。

FATAL EXCEPTION: main
java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

由此可見:inflate(resId, null) 確實不能正確處理寬高;但 inflate(resId, parent, false) 並非與前者一致,它能完美顯示寬高;而 inflate(resId, parent, true) 則會報錯。文章開頭的理解,被徹底推翻。

三、源碼解析

這三個方法最終都會走到同一個核心方法:

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
    // ...
    View result = root;
    // ...
    // 創建 temp 視圖
    ViewGroup.LayoutParams params = null;
    if (root != null) {
        params = root.generateLayoutParams(attrs);
        if (!attachToRoot) {
            temp.setLayoutParams(params); // 未附加時,為 temp 設置 LayoutParams
        }
    }
    // 解析子節點
    rInflate(parser, temp, attrs, true);
    // root 不為 null 且 attachToRoot 為 true 時,把 temp 加入 root
    if (root != null && attachToRoot) {
        root.addView(temp, params);
    }
    // root 為 null 或 attachToRoot 為 false 時,返回 temp
    if (root == null || !attachToRoot) {
        result = temp;
    }
    return result;
}

梳理三種情況的行為:

  • Inflate(resId, null):只創建 temp 並返回,此時 temp 的 LayoutParams 為 null。
  • Inflate(resId, parent, false):創建 temp,執行 temp.setLayoutParams(params) 後返回 temp。
  • Inflate(resId, parent, true):創建 temp,執行 root.addView(temp, params),最後返回的是 root。

為什麼 Inflate(resId, null) 無法正確處理寬高?因為 layout_width、layout_height 是相對於父容器設置的,必須依賴父容器生成的 LayoutParams,而此時 temp 的 LayoutParams 為 null,自然無法生效。

而寫法三之所以報錯,是因為它調用了 root.addView(temp, params),此時的 root 就是我們的 ListView。ListView 是 AdapterView 的子類,其 addView 方法被重寫為直接拋異常:

@Override
public void addView(View child) {
    throw new UnsupportedOperationException("addView(View) is not supported in AdapterView");
}

四、進一步驗證

再寫一個例子:主 Activity 不調用 setContentView,只執行三個 inflate 方法,parent 傳入 Activity 的內容區域 android.R.id.content(一個 FrameLayout)。

View view1 = mInflater.inflate(R.layout.activity_main, null);
View view2 = mInflater.inflate(R.layout.activity_main, (ViewGroup) findViewById(android.R.id.content), false);
View view3 = mInflater.inflate(R.layout.activity_main, (ViewGroup) findViewById(android.R.id.content), true);
Log.e(TAG, "view1.layoutParams = " + view1.getLayoutParams());
Log.e(TAG, "view2.layoutParams = " + view2.getLayoutParams());
Log.e(TAG, "view3 = " + view3);

輸出結果印證了我們的推斷:

view1.layoutParams = null
view2.layoutParams = android.widget.FrameLayout$LayoutParams@...
view3 = android.widget.FrameLayout@...

雖然沒有調用 setContentView,界面上卻顯示了按鈕——正是因為 view3 那行代碼內部執行了 root.addView(temp, params),把按鈕添加進了內容區域。

五、從 ViewGroup 與 View 的視角解讀

最後從測量機制解釋為何 LayoutParams 為 null 就無法處理寬高:

ViewGroup 的 onMeasure 會根據子 View 的 LayoutParams 設置測量模式與測量值:

  • 寬為 MATCH_PARENT 或固定值(>0):模式為 MeasureSpec.EXACTLY;
  • 寬為 WRAP_CONTENT:模式為 MeasureSpec.AT_MOST。

而 View 的 onMeasure 則根據傳入的模式計算自身尺寸:AT_MOST 時自行計算,EXACTLY 時直接取指定值。

可見,View 的準確寬高高度依賴於 LayoutParams。當 LayoutParams 為 null,系統就無從得知該如何測量,寬高自然失效。這正是 inflate(resId, null) 無法正確處理寬高的根本原因。

理解了這一層,以後在實際開發中,你就能根據場景準確選擇合適的 inflate 寫法了。

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