android style attribute 学习记录

要使用自定义属性需要如下几步:
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绘制布局

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值