Android中自定義控件的declare-styleable屬性重用方案
最近接觸了Android自定義控件,涉及到自定義xml中得屬性(attribute),其實也很簡單,但是寫著寫著,發(fā)現(xiàn)代碼不完美了,就是在attrs.xml這個文件中,發(fā)現(xiàn)屬性冗余,于是就想有沒有類似屬性繼承或者include之類的方法.本文將就declare-stylable中屬性重用記錄一下.
不完美的代碼
<?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>
如上面代碼,在ExTextView和ExEditText這個stylable中有著重復的屬性申明.雖然上面可以工作,但是總感覺寫的不專業(yè),于是尋找優(yōu)化方法.
這樣可以么
嘗試著為declare-stylable指定一個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插件的問題.其他人也遇到了這樣的問題. 這個方法目前是不行的.
終極答案
實際上我們可以在declare-stylable之前,申明要多次使用的屬性,在declare-stylable節(jié)點內(nèi)部,只需調(diào)用即可.具體代碼如下.
<?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文件重新生成.
延伸閱讀
- android 自定義控件 自定義屬性詳細介紹
- android自定義倒計時控件示例
- Android自定義表格控件滿足人們對視覺的需求
- android圖像繪制(四)自定義一個SurfaceView控件
- android自定義按鈕示例(重寫imagebutton控件實現(xiàn)圖片按鈕)
- android開發(fā)教程之自定義控件checkbox的樣式示例
- Android開發(fā)技巧之在a標簽或TextView控件中單擊鏈接彈出Activity(自定義動作)
- Android自定義播放器控件VideoView
- android自定義控件和自定義回調(diào)函數(shù)步驟示例
- 輕松實現(xiàn)可擴展自定義的Android滾輪時間選擇控件
- Android自定義控件屬性詳細介紹
相關文章
Android使用Activity實現(xiàn)從底部彈出菜單或窗口的方法
這篇文章主要介紹了Android使用Activity實現(xiàn)從底部彈出菜單或窗口的方法,涉及Android布局、窗口、事件監(jiān)聽、權限控制等相關操作技巧,需要的朋友可以參考下2017-07-07

