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

前端之家收集整理的这篇文章主要介绍了在自定义控件中读取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);
    }
原文链接:https://www.f2er.com/xml/298078.html

猜你在找的XML相关文章