在自定义控件的时候,有些配置文件可以用代码来写,但是为了降低耦合,最好的方式是放在配置文件中,比如生成布局控件的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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。