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

Android 自訂屬性 attr 入門:它是什麼、該怎麼定義

編輯:關於 Android 開發

Android 自訂屬性 attr 入門:它是什麼、該怎麼定義

開發自訂 View 時,一定會遇到這種需求:希望元件在 XML 裡也能像系統控制項一樣設定屬性,例如 <com.example.MyView app:radius="8dp" />。這就要靠 attr 這個資源型別。

基本做法分三步:

  1. 在 res/values/attrs.xml 中用 <declare-styleable name="MyView"> 包住若干 <attr>,宣告名稱與型別(reference、color、dimension、integer、enum、flag 等)。
  2. 在布局檔的根節點加上 xmlns:app="https://schemas.android.com/apk/res-auto",然後用 app: 前綴設定這些屬性。
  3. 在自訂 View 的建構式中,透過 context.obtainStyledAttributes(attrs, R.styleable.MyView) 讀取值,取完記得呼叫 recycle()。

attr 的價值在於把「可調參數」從程式碼搬到 XML,讓樣式與版面配置可以交給設計與版面檔處理,也能用 style 一次套用到多處。命名上建議加上自有的前綴(例如 cv_radius),避免與其他函式庫的屬性衝突。

延伸閱讀(原文出處):https://androidbook.com/item/4169

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