LayoutInflater 是 Android 視圖構建的核心類,負責將 XML 佈局文件「充氣」為 View 物件樹。不同於 findViewById() 尋找現有 View,LayoutInflater.inflate() 是創建新 View 階層。本文深入解析其工作原理、三種取得方式、四種 inflate 簽名差異、Dialog/Adapter/Fragment 中的正確用法、常見坑點與效能優化策略。
XmlPullParser 解析,透過 Factory2 / Factory 創建 View(支援自定義 View 攔截)。LayoutInflater 內部緩存已解析的 XML 結構(ParsePackage),二次充氣大幅加速。// 1. Context 系統服務(最常用、生命週期跟隨 Context)
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Activity 便利方法(內部同樣呼叫系統服務)
LayoutInflater inflater = getLayoutInflater(); // 或 LayoutInflater.from(context)
// 3. 從現有 View 取得(確保使用同一 Configuration/Theme)
LayoutInflater inflater = LayoutInflater.from(view.getContext());
建議:優先使用 LayoutInflater.from(context),簡潔且自動處理 ContextWrapper。
// 1. 僅資源 ID,掛載給 root,返回 root
View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
// 2. 指定是否 attachToRoot(最常用、最靈活)
View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
// 3. 從 XmlPullParser 充氣(罕用)
View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
// 4. 完整參數:資源 ID、root、attachToRoot、LayoutParams 生成標誌
View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot, @Nullable LayoutParams params)
| attachToRoot | root 非 null | root 為 null |
|---|---|---|
| true | 充氣後的 View 加入 root,返回 root。LayoutParams 來自 root 類型。 | 拋出異常 (需要 root 以生成 LayoutParams) |
| false | 充氣後的 View 不加入 root,返回 充氣的根 View。LayoutParams 依 root 類型生成但不套用。 | 返回充氣的根 View,LayoutParams 為 null(需手動設定)。 |
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// ✅ 正確:parent 提供 LayoutParams,attachToRoot=false
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
// Dialog
View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_layout, null);
new AlertDialog.Builder(context).setView(dialogView).show();
// BottomSheetDialogFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ✅ container 非 null,attachToRoot=false,Framework 會自行加入
return inflater.inflate(R.layout.bottom_sheet, container, false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ✅ 必須 attachToRoot=false,FragmentManager 會負責加入 container
return inflater.inflate(R.layout.fragment_layout, container, false);
}
View child = LayoutInflater.from(context).inflate(R.layout.child_item, parentContainer, true);
// 直接加入並返回 parentContainer,適用於線性添加場景
| 錯誤寫法 | 後果 | 正確寫法 |
|---|---|---|
inflater.inflate(R.layout.item, null) 在 Adapter 中 | 失去父容器 LayoutParams,導致 match_parent 失效、邊距異常 | inflate(layout, parent, false) |
inflate(layout, parent, true) 在 Fragment/Adapter | View 重複加入、IllegalStateException (已有父親) | inflate(layout, parent, false) |
| 在非 UI 執行緒呼叫 inflate | UI 執行緒違規、ANR | 預先在背景執行緒解析 XML (LayoutInflater.parseInclude) 或使用 ViewStub |
| 重複 inflate 同一資源無緩存 | 解析開銷大,列表滑動卡頓 | 複用 ViewHolder、ViewStub 延遲充氣、預先充氣緩存 |
<merge><TextView/><TextView/></merge> 充氣到 LinearLayout 直接變兩個 TextView 孩子)。AsyncLayoutInflater (API 24+) 在背景執行緒充氣,回調主執行緒加入樹,減少主執行緒阻塞。LayoutInflater inflater = LayoutInflater.from(context);
inflater.setFactory2(new LayoutInflater.Factory2() {
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
if ("CustomButton".equals(name)) {
return new CustomButton(context, attrs); // 直接返回自定義 View 實例
}
return null; // 繼續預設創建流程
}
@Override public View onCreateView(String name, Context context, AttributeSet attrs) { return null; }
});
應用場景:主題換膚自動替換 View、字體全域替換、元件庫自動註冊。
掌握 LayoutInflater 的 attachToRoot 語意、正確傳遞 parent 以獲取 LayoutParams、善用 ViewStub/merge/AsyncLayoutInflater 優化效能,是 Android UI 開發從「能跑」到「穩、快、好維護」的關鍵分水嶺。