在自定义控件中读取XML配置属性的值


在自定义控件的时候,有些配置文件可以用代码来写,但是为了降低耦合,最好的方式是放在配置文件中,比如生成布局控件的XML中。

今天遇到的需求就是一个自定义控件的Title,如果用代码传一个值进去也是可以的,但是这个自定义控件的基础配置信息还是希望能喝TextView一样设置Text内容就显示到控件上,所有查了一下资料实现了这个功能。

第一步:设置自定义属性

         xmlns:自定义前缀="http://schemas.android.com/apk/res/包名"

例子: xmlns:line="http://schemas.android.com/apk/res/com.test.view"

第二步:res/values文件下定义一个attrs.xml文件

` <declare-styleable name="statisticLineView">
 <attr name="lineTitle" format="string" />
 </declare-styleable>`

更多attrs配置信息:http://googlers.iteye.com/blog/1122585

第三步:在自定义控件布局中配置属性

 private void getSet(Context context, AttributeSet attrs) {
        TypedArray aTypedArray = context.obtainStyledAttributes(attrs, R.styleable.statisticLineView);
        titleStr = aTypedArray.getString(R.styleable.statisticLineView_lineTitle);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值