天天看點

declare-styleable自定義控件屬性

今天研究了一下android控件的自定義屬性的使用:友善以後的使用,防止忘記就記錄一下。

第一步:  在values檔案夾下面建立attr.xml檔案,在這個檔案中定義自定義屬性

declare-styleable自定義控件屬性

比如:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MultiDirectionSlidingDrawer">
	    <attr name="handle" format="dimension"></attr>
	    <attr name="content" format="dimension"></attr>
	    <attr name="allowSingleTap" format="boolean"></attr>
	    <attr name="animateOnClick" format="boolean"></attr>
	    <attr name="bottomOffset" format="dimension"></attr>
	    <attr name="topOffset" format="dimension"></attr>
            <attr name="direction" >
                <enum name="rightToLeft" value="0" />
	            <enum name="bottomToTop" value="1" />
	            <enum name="leftToRight" value="2" />
	            <enum name="topToBottom" value="3" />
            </attr>
    </declare-styleable>
</resources>
           

第二步:使用,自定義屬性的使用是在布局中使用

declare-styleable自定義控件屬性

第三步:在自定義控件中使用。

注意要在有三個參數的構造方法中才能擷取到。

declare-styleable自定義控件屬性

第一部分的命名就是declare-styleable 後面name對應的值

使用後記得調用一下gc釋放資源

a.recycle();  
           

關于自定義屬性的設定問題:

  fomat的屬性自己定義  根據自己的需要來選擇string , integer , dimension , reference , color , enum......

reference:參考指定Theme中資源ID。

dimension:尺寸值

float:浮點型

boolean:布爾值

integer:整型

string:字元串

fraction:百分數

flag:位或運算

Color:顔色

enum:枚舉

其他都很簡單,一看就會,枚舉的特殊些,就是把能選的值列舉出來,在布局中設定屬性的時候就隻能選擇在attr.xml中定義的枚舉的值

比如:

<attr name="direction" >
            <enum name="rightToLeft" value="0" />
	        <enum name="bottomToTop" value="1" />
	        <enum name="leftToRight" value="2" />
	        <enum name="topToBottom" value="3" />
        </attr>
           

在使用的時候如圖: 在構造方法中取值就會取到對應的value中的值。

declare-styleable自定義控件屬性

屬性定義時可以指定多種類型值:

1
2
3
      
<declare-styleable name = "名稱">    
	<attr name="background"       format="reference|color" />
    </declare-styleable>      

使用:

1
      
<ImageView android:background = "@drawable/圖檔ID|#00FF00"/>      

繼續閱讀