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

LayoutInflater.inflate() 參數解析:root 與 attachToRoot

編輯:關於 Android 開發

LayoutInflater.inflate() 參數研究

LayoutInflater.inflate() 是 Android 開發中常用的方法,主要用來將 XML 版面轉換成 View 物件。理解 root 與 attachToRoot 兩個參數,能避免版面套用錯誤。

方法重載

inflate 有多種重載形式,常見包括傳入資源 ID 或 XmlPullParser,並搭配 root 與 attachToRoot。最終多數會導向同一套核心邏輯。

root 的作用

當 root 為空時,XML 根節點的 LayoutParams 通常不會被套用,而是使用目前父容器的設定。當 root 不為空時,root 會作為版面參數的計算依據。

attachToRoot 的作用

attachToRoot 決定是否要把 inflate 出來的 View 直接加入 root。若為 true,該 View 會被掛載到 root 下,並保留自身 LayoutParams。若為 false,則只回傳該 View,不立即加入 root。

常見結論

簡化來說:root 存在且 attachToRoot 為 true 時,會將 XML 掛載到 root 並回傳 root;attachToRoot 為 false 時,通常回傳 XML 的根 View。

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