首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Android 自定義 View 屬性復用:attrs.xml 中 declare-styleable 共享 attr 定義

     編輯:Java 相關知識

問題:多個 Styleable 重複聲明相同屬性

<declare-styleable name="ExTextView">
    <attr name="enableOnPad" format="boolean"/>
    <attr name="supportDeviceType" format="reference"/>
</declare-styleable>
<declare-styleable name="ExEditText">
    <attr name="enableOnPad" format="boolean"/> <!-- 重複 -->
    <attr name="supportDeviceType" format="reference"/> <!-- 重複 -->
</declare-styleable>

代碼冗余、維護成本高、易出現不一致。

嘗試失敗:parent 繼承

<declare-styleable name="ExEditText" parent="ExTextView"/>

雖然語法通過,但 R.styleable.ExEditText_enableOnPad **不會生成**,導致代碼中無法引用,ADT/AAPT 已知限制。

正解:全局 attr 定義 + 引用

在 <resources> 根節點直接定義 <attr>,再在各 declare-styleable 中**僅引用名稱**:

<resources>
    <!-- 全局定義一次 -->
    <attr name="enableOnPad" format="boolean"/>
    <attr name="supportDeviceType" format="reference"/>

    <declare-styleable name="ExTextView">
        <attr name="enableOnPad"/>
        <attr name="supportDeviceType"/>
    </declare-styleable>

    <declare-styleable name="ExEditText">
        <attr name="enableOnPad"/>
        <attr name="supportDeviceType"/>
    </declare-styleable>
</resources>

效果驗證

  • R.attr.enableOnPad 唯一生成;
  • R.styleable.ExTextView 包含 enableOnPad 索引;
  • R.styleable.ExEditText 同樣包含,索引值**與 ExTextView 完全一致**;
  • Java/Kotlin 代碼中 TypedArray.getBoolean(R.styleable.ExTextView_enableOnPad, ...) 正常工作。

最佳實踐建議

  1. 項目建立 attrs_base.xml 集中定義所有通用屬性;
  2. 各模塊 attrs_xxx.xml 僅引用,不重複定義 format;
  3. 修改屬性類型/名稱只需改一處;
  4. 每次修改後 **Clean Project → Rebuild** 確保 R 文件重新生成。

延伸閱讀

StackOverflow 討論:How to declare several stylable attributes with the same name for different tags

一處定義、多處引用,是資源文件規範化的核心原則。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved