步骤
1.在values文件下,创建attrs.xml(文件名可换)
2.在布局xml文件中书写名称空间,使用自定义属性
3.在自定义view中获取属性的配置值,进行使用
<resources>
<declare-styleable name="MyToggleView">
<attr name="slide_background" format="reference"/>
<attr name="toggle_background" format="reference"/>
<attr name="state" format="boolean"/>
</declare-styleable>
</resources>
使用
MyToggleView:state="true"
MyToggleView:slide_background="@mipmap/slide_button"
MyToggleView:toggle_background="@mipmap/switch_background"
名称空间
xmlns:MyToggleView="http://schemas.android.com/apk/res-auto"
获取属性配置
String nameSpace = "http://schemas.android.com/apk/res-auto";
int slideBackground = attrs.getAttributeResourceValue(nameSpace, "slide_background", -1);
int switchToggle = attrs.getAttributeResourceValue(nameSpace, "toggle_background", -1);
boolean state = attrs.getAttributeBooleanValue(nameSpace, "state", false);
attrs.xml中format的值总结
“reference”—引用
“color”—颜色
“boolean”—布尔值
“dimension”—尺寸值
“float”—浮点值
“integer”—整型值
“string” —字符串
“fraction” —百分数,比如50%
枚举类型
< attr name=”orientation”>
< enum name=”horizontal” value=”0” />
< enum name=”vertical” value=”1” />
< /attr>
标志位、位或运算,格式如下
< attr name=”windowSoftInputMode”>
< flag name = “stateUnspecified” value = “0” />
< flag name = “stateUnchanged” value = “1” />
< flag name = “stateHidden” value = “2” />
< flag name = “stateAlwaysHidden” value = “3” />
< flag name = “stateVisible” value = “4” />
< flag name = “stateAlwaysVisible” value = “5” />
< flag name = “adjustUnspecified” value = “0x00” />
< flag name = “adjustResize” value = “0x10” />
< flag name = “adjustPan” value = “0x20” />
< flag name = “adjustNothing” value = “0x30” />
< /attr>