最近接觸了Android自定義控件,涉及到自定義xml中得屬性(attribute),其實也很簡單,但是寫著寫著,發(fā)現(xiàn)代碼不完美了,就是在attrs.xml這個文件中,發(fā)現(xiàn)屬性冗余,于是就想有沒有類似屬性繼承或者include之類的方法.本文將就declare-stylable中屬性重用記錄一下.
不完美的代碼
<declare-styleable name="ExEditText">
<attr name="enableOnPad" format="boolean" />
<attr name="supportDeviceType" format="reference"/>
</declare-styleable>
</resources>
如上面代碼,在ExTextView和ExEditText這個stylable中有著重復的屬性申明.雖然上面可以工作,但是總感覺寫的不專業(yè),于是尋找優(yōu)化方法.
這樣可以么
嘗試著為declare-stylable指定一個parent,如下代碼
<declare-styleable name="ExEditText" parent="ExTextView">
</declare-styleable>
</resources>
終極答案
實際上我們可以在declare-stylable之前,申明要多次使用的屬性,在declare-stylable節(jié)點內部,只需調用即可.具體代碼如下.
<declare-styleable name="ExEditText">
<attr name="enableOnPad"/>
<attr name="supportDeviceType"/>
</declare-styleable>
</resources>
延伸閱讀
新聞熱點
疑難解答
圖片精選