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

Android LayoutInflater 原理解析:inflate 方法與 attachToRoot 的差異

編輯:關於 Android 程式設計

LayoutInflater 是 Android 中常用的版面載入工具,可將 res/layout 下的 XML 版面轉成 View 或 ViewGroup。它與 findViewById 不同:findViewById 是在既有版面中尋找元件,LayoutInflater 則是動態建立版面。

取得 LayoutInflater

常見寫法有三種:透過 getSystemService(Context.LAYOUT_INFLATER_SERVICE)、呼叫 Activity 的 getLayoutInflater(),或使用 LayoutInflater.from(context)。三者本質相同,最終都會取得系統的 LayoutInflater 服務。

inflate 方法概覽

inflate 有多重重載,最常用的是指定版面資源與父容器。例如 inflate(resource, root) 與 inflate(resource, root, attachToRoot)。其中 root 代表可能用來產生 LayoutParams 的父容器,attachToRoot 則決定是否直接把載入的 View 加入 root。

三種常見寫法的差異

以下以載入 button.xml 為例,分別使用 inflate(R.layout.button, null)、inflate(R.layout.button, group, false)、inflate(R.layout.button, group, true)。

當 root 傳入 null 時,系統無法取得父容器的 LayoutParams,因此 XML 中設定的寬高可能不會如預期生效。

當 root 不為 null 且 attachToRoot 為 false 時,系統會根據 root 產生 LayoutParams,但不會自動把 View 加入 root。因此 XML 的寬高設定可以生效,之後再由開發者自行呼叫 addView。

當 attachToRoot 為 true 時,inflate 內部已經執行加入父容器的動作。如果外部再次呼叫 group.addView(view),就可能拋出「指定子項已有父容器」的例外。

原始碼邏輯

LayoutInflater 的核心流程會先建立 XML 根節點對應的 View,接著判斷 root 是否為空。若 root 不為空且 attachToRoot 為 false,會先將產生的 LayoutParams 設定到 temp;若 root 不為空且 attachToRoot 為 true,則直接呼叫 root.addView(temp, params)。最後,當 root 為 null 或 attachToRoot 為 false 時,方法會回傳 temp 作為結果。

結論

若希望 XML 的寬高生效,建議傳入有效的 root,並將 attachToRoot 設為 false,再自行 addView;若希望 inflate 直接完成加入父容器,則將 attachToRoot 設為 true,且不要再重複 addView。理解這項差異,可避免版面參數失效或重複加入造成的崩潰。

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