Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android TypedArray 原始碼解析

編輯:Android 資訊

TypedArray 是什麼

在自訂 View 時,常需要從 XML 讀取自訂屬性。TypedArray 就是封裝這些屬性的工具,能依型別取得字串、整數、布林、顏色、尺寸等資料。

取得與回收

通常透過 Context 的 obtainStyledAttributes 取得 TypedArray。使用完畢後應呼叫 recycle,讓物件回到資源池,避免記憶體浪費。

內部資料排列

TypedArray 的 mData 會以每組六個整數保存一個屬性的相關資訊,例如型別、資料、資源 ID、密度等。mIndices 的第一個值代表實際使用到的屬性數量,後續則是屬性索引。

讀取值

getString、getInt、getBoolean、getColor 等方法會先定位屬性,再依型別轉換。若 XML 型別與宣告格式不符,執行時可能出現錯誤,需要修正 attrs 定義並重新編譯。

常用場景

例如取得 layout_width 與 layout_height 時,會使用 getLayoutDimension。自訂 View 若要正確支援 match_parent 或 wrap_content,通常需要在 onMeasure 中自行計算尺寸。

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