安卓自定义控件之自定义属性
自定属性的步骤:
1、在attrs.xml文件中声明属性,有属性名:name和格式format。如:
<declare-styleable name="MyToggleButtonAttr"> <attr name="ToggleButtonBackground" format="reference" /> <attr name="SlideButton" format="reference" /> <attr name="CurrentState" format="boolean" /> </declare-styleable>
declare-styleable代表了一个属性集,attr子标签代表一个属性
format常用类型:reference 引用、color 颜色、boolean 布尔值、dimension 尺寸值
float 浮点值、integer 整型值、string 字符串、enum 枚举值
2、在布局中使用自定义属性,使用之前必须先声明命名空间,如:
xmlns:jsako="http://schemas.android.com/apk/res/com.jsako.togglebutton"
格式为:xmlns:jsako="http://schemas.android.com/apk/res/应用程序包名
使用自定义属性,如:
<com.jsako.togglebutton.view.MyToggleButton android:id="@+id/mytb" android:layout_width="wrap_content" android:layout_height="wrap_content" jsako:ToggleButtonBackground="@drawable/switch_background" jsako:SlideButton="@drawable/slide_button" jsako:CurrentState="false" android:layout_centerInParent="true" />
格式为:命名空间:属性名(attr标签下name属性对应的值)="(format对应的格式)"
3、在自定义view构造方法中,通过解析AttributeSet对象,获得所需要的属性值
此时可以通过系统提供TypedArray工具类,更好解析出自定义属性
1 TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.MyToggleButtonAttr); 2 for(int i=0;i<typedArray.getIndexCount();i++){ 3 //遍历typeArrayCount 4 int index=typedArray.getIndex(i); 5 switch(index){ 6 case R.styleable.MyToggleButtonAttr_CurrentState: 7 currentState=typedArray.getBoolean(index, false); 8 break; 9 case R.styleable.MyToggleButtonAttr_SlideButton: 10 slideBtnId=typedArray.getResourceId(index,-1); 11 if(slideBtnId==-1){ 12 throw new RuntimeException("请正确设置拖动按纽图片"); 13 } 14 break; 15 case R.styleable.MyToggleButtonAttr_ToggleButtonBackground: 16 slideBackgroundId=typedArray.getResourceId(index,-1); 17 if(slideBackgroundId==-1){ 18 throw new RuntimeException("请正确设置拖动按纽图片"); 19 } 20 break; 21 }
浙公网安备 33010602011771号