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

Android 自定義控件:obtainStyledAttributes 系列函數詳解

編輯:關於 Android 開發

Android 自定義控件:obtainStyledAttributes 系列函數詳解

在開發自定義控件時,經常需要讀取 XML 中設定的屬性。這時通常會用到 obtainStyledAttributes 或 obtainAttributes。這兩個系列函數會返回 TypedArray,讓我們可以根據屬性名稱取得對應值。本文將釐清常見函數的差異、使用場景與屬性優先級。

一、常見函數概覽

  • obtainStyledAttributes(int[] attrs)
  • obtainStyledAttributes(int resid, int[] attrs)
  • obtainAttributes(AttributeSet set, int[] attrs)
  • obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)

其中,前兩個與 Theme 或 Style 資源有關;第三個直接從 AttributeSet 讀取;第四個則是最常用、也最靈活的寫法。

二、準備自定義屬性

通常在 values 下建立 attrs.xml,並使用 declare-styleable 定義自定義屬性。布局中則加入自定義命名空間,讓控件可以讀取這些屬性。

三、obtainStyledAttributes(int[] attrs)

這個函數會從主題中讀取屬性值。也就是說,即使布局中設定了屬性,最終值也可能由 Theme 決定。因此,它較少直接用於普通布局屬性解析。

四、obtainStyledAttributes(int resid, int[] attrs)

這個函數會從指定的 Style 資源中讀取屬性值。它與上一個函數相似,只是屬性來源改為 resid 指定的樣式資源。

五、obtainAttributes(AttributeSet set, int[] attrs)

這個函數直接從 AttributeSet 讀取值,不會套用主題或樣式。也就是說,它讀取的是 XML 布局中明確設定的屬性值。如果布局中沒有設定,可能會得到預設值或引發問題。

六、obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)

這是最推薦的寫法。它會綜合 AttributeSet、樣式資源與主題預設值來決定最終屬性值。其優先級通常為:

  • AttributeSet 中明確設定的值。
  • AttributeSet 中 style 屬性指定的樣式。
  • defStyleAttr 指定的預設樣式。
  • defStyleRes 指定的預設樣式資源。
  • 主題中的預設值。

七、總結

自定義控件屬性解析的核心,是理解屬性值到底來自 XML、Style、Theme,還是程式預設值。日常開發中,最常用的是 obtainAttributes 與帶 AttributeSet 的 obtainStyledAttributes。掌握優先級後,就能避免屬性不生效、主題覆蓋與預設值混亂等問題。

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