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

Android 自訂控件中 declare-styleable 屬性重用的正確寫法

編輯:Android 開發實例

最近在寫 Android 自訂控件,需要定義 XML 屬性。整體並不難,但寫到 attrs.xml 時發現屬性重複宣告得很厲害,於是開始找有沒有類似「屬性繼承」或 include 的做法。本文記錄 declare-styleable 中屬性重用的可行方案。

不完美的寫法

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <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>
</resources>

兩個 styleable 中的屬性宣告一模一樣。程式能跑,但看起來就是不夠專業,於是繼續找優化方式。

試試 parent 屬性?

<?xml version="1.0" encoding="utf-8"?>
<resources>

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

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

    </declare-styleable>
</resources>

attrs.xml 確實沒報語法錯誤,但使用 R.styleable.ExEditText_supportDeviceType 時,R 檔案裡根本沒有生成這個常數,重新清理專案也一樣。這應該是 ADT 插件的問題,其他人也遇過相同狀況。結論是:這個方法目前行不通。

可行方案:先宣告 attr,再重複引用

正確做法是在 declare-styleable 之前先把共用屬性宣告一次,之後在各 styleable 內部只需引用名稱,不必重複寫 format。

<?xml version="1.0" encoding="utf-8"?>
<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>

每次引用 attr 之後,建議清理一次專案,確保 R 檔案重新生成。

補充

這套寫法的好處不只是少打字:屬性的 format 只有一份來源,日後要從 boolean 改成 enum 時不必逐處修改,也不容易漏改造成型別不一致。另外若多個 styleable 共用大量屬性,也可以考慮用 attr 搭配自訂 View 的構造函式讀取 ObtainStyledAttributes() 時一次帶入多組,讓程式碼側的解析邏輯跟著收斂。

延伸閱讀:https://stackoverflow.com/questions/18827875/how-to-declare-several-stylable-attributes-with-the-same-name-for-different-tags

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