如下attrs相关内容转自:http://www.cnblogs.com/mstk/p/3575086.html
控件有很多属性,如android:id、android:layout_width、android:layout_height等,但是这些属性都是系统自带的属性。使用attrs.xml文件,可以自定义属性。本文在Android自定义控件的基础上,用attrs.xml文件自己定义了属性。
首先,在values文件夹下,新建一个attrs.xml文件,文件内容如下:
1
2
3
4
5
6
7
|
<?xml version=
"1.0"
encoding=
"utf-8"
?>
<resources>
<declare-styleable name=
"CustomView"
>
<attr name=
"tColor"
format=
"color"
/>
<attr name=
"tSize"
format=
"dimension"
/>
</declare-styleable>
</resources>
|
其中,<declare-styleable name="CustomView">表明样式名称为CustomView,下面包含了两个自定义属性tColor和tSize,其中tColor是颜色(color)类的属性,tSize是尺寸(dimension)类的属性。
如下AttributeSet TypedArray 相关内容转自:http://blog.youkuaiyun.com/bingospunky/article/details/39890053
AttributeSet这个类就是代表xml里一个节点下面的属性的集合,这个类一般都是系统在生成有xml配置的组件时生成,我们一般不去生成该对象,在使用的时候一般都是把AttributeSet封装成TypedArray进行使用。
TypedArray
我认为这个类是学习自定义属性最重要的,首先来看它是什么:
是一个用于存放恢复obtainStyledAttributes(AttributeSet, int[], int, int)或 obtainAttributes(AttributeSet, int[])
值的一个数组容器,当操作完成以后,一定要调用recycle()方法。用于检索的索引值在这个结构对应的位置给obtainStyledAttributes属性
重点是学习这个类的实例是怎么来的?一般是由context.obtainStyledAttributes这个方法,有4个重载的方法。
我们来看
这个方法就是从资源里挑出一些属性来,按照顺序放到TypedArray里,参数可以控制从哪里挑选属性,挑选哪些。
参数set:挑选属性的出处是AttributeSet。
参数attrs:这是一个属性的数组,只是哪些属性被挑选出来,在之前看R文件的时候R.styleable.button1就是这样的数组,我们可以自己new这样的数组,再赋值。
参数defStyleAttr:挑选属性的出处是defStyleAttr。
参数defStyleRes:挑选属性的出处是defStyleRes。
在自定义view的代码中引入自定义属性,修改构造函数 context通过调用obtainStyledAttributes方法来获取一个TypeArray,然后由该TypeArray来对属性进行设置 obtainStyledAttributes方法有三个,我们最常用的是有一个参数的obtainStyledAttributes(int[] attrs),其参数直接styleable中获得 TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView); 调用结束后务必调用recycle()方法,否则这次的设定会对下次的使用造成影响
代码部分: