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

Android LayoutInflater 深入解析:inflate 三個參數的差異

編輯:關於 Android 程式設計

常見誤解

許多開發者會以為 inflate(resource, null)、inflate(resource, root, false) 與 inflate(resource, root, true) 的差別只在於是否把 View 加入父容器。實際上,這三者在 LayoutParams 與回傳值上都有明顯差異。

實作驗證

在 ListView 的 getView 中,若使用 inflate(item, null),item 根 View 的寬高可能無法正確套用;若使用 inflate(item, parent, false),LayoutParams 會被正確產生;若使用 inflate(item, parent, true),則可能觸發 AdapterView 不支援 addView 的錯誤。

源碼解析

inflate 內部會先建立 temp View。若 root 不為 null,會透過 root.generateLayoutParams 產生 LayoutParams。若 attachToRoot 為 false,就把 LayoutParams 設定到 temp;若 attachToRoot 為 true,則直接把 temp 加入 root。最後,若 root 為 null 或 attachToRoot 為 false,回傳的是 temp;否則回傳 root。

為什麼 LayoutParams 很重要

ViewGroup 在量測子 View 時,會依 LayoutParams 判斷寬高模式。若 LayoutParams 為 null,就無法正確處理 match_parent 或固定寬高。因此,inflate(resource, null) 容易造成寬高失效。

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