要使用自定义属性需要如下几步:
1 定义属性名称
2 指定属性的值
3 代码中获取属性值
4 view中使用获取的值
定义属性名称
属性名称在res/values/attrs.xml中定义,有两种方式
1 单独定义
<resources>
<attr name="CustomizeStyle" format="reference" /> //reference 另一个资源的id,如一个图片,一个style等
</resources>
2 定义到一组里
<resources>
<declare-styleable name="Customize">
<attr name="attr_one" format="string" />
<attr name="attr_two" format="string" />
<attr name="attr_three" format="string" />
<attr name="attr_four" format="string" />
</declare-styleable>
</resources>
两种声明方式对于attr标签下的值没有实质影响,都可以R.attr.XXX访问到,不同是第二种可以通过R.styleable.xxx一下获取一个数组,数组的每个值是一个attr,数值和R.attr.xxx一样
对属性赋值
对属性赋值有三种方式
1 在布局文件中使用
2 在style中使用
3 在theme中使用
1 在布局文件中使用自定义属性需要先声明域名,格式如下:
xmlns:xxx=”http://schemas.android.com/apk/res/定义属性的应用的包名”
然后在view中使用xxx:属性名=属性值
2 在style中使用
直接在style标签下添加属性值
3 在theme中使用
直接添加标签,或添加style引用,这影响读取属性值的顺序
获取属性值
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Customize, defStyle, R.style.DefaultCustomizeStyle);
String one = a.getString(R.styleable.Customize_attr_one);
a.recycle();
一般就是这么读取,有优先级:
布局xml>style>Theme中的默认Sytle(第三参数)>默认Style(通过obtainStyledAttributes的第四个参数指定)>在Theme中直接指定属性值
4 读取值后可以用作view绘制布局