一、自定义属性
首先在values的资源文件夹下创建一个attrs的文件。
属性写上
<declare-styleable name="CustomView">
<attr name="color" format="color"/>
</declare-styleable>
其中declare-styleable下的name是你的自定义控件的名字,attr标签下的name是你要添加的属性的名字,format是它的格式。
共有10种:
1.reference:引用某一资源ID。
使用:
app:reference = "@color/颜色ID"
或者
app:reference = "#aabbcc"
2.color:颜色值
使用:
app:color="#aabbcc"
3.boolean:布尔值。(不做解释)
4.dimension:尺寸值。
例如dp和sp等值要使用这个格式
app:dimension="30dp"
5.float:浮点值。
app:float="0.7"
6.integer:整型值。(不做解释)
7.string: 字符串。(不做解释)
8.fraction:百分数。
app:fraction="300%"
9.enum:枚举值。
定义:
<declare-styleable name="CustomView">
<attr name="enum">
<enum name="example_one" value="0" />
<enum name="example_two" value="1" />
</attr>
</declare-styleable>
使用:
app:enum = "exampleone"
10.flag:位或运算。
定义:
<attr name="flags">
<flag name = "example_one" value = "1"/>
<flag name = "example_two" value = "2"/>
<flag name = "example_three" value = "3"/>
<flag name = "example_four" value = "4"/>
</attr>
使用:
app:flags="example_four|example_one|example_two|example_three"
另外需要注意的是: 属性定义时可以指定多种类型值。中间使用 | 分隔即可。
二、获取自定义的属性
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
int customColor = ta.getColor(R.styleable.CustomView_color, Color.BLUE);
ta.recycle();
}
获取属性就是通过TypedArray对象来get,什么类型的属性就用对应的get方法。
注意使用完TypedArray对象后需要释放它。ta.recycle()。
原因是它是一个池+单例模式,程序在运行时维护了一个 TypedArray的池,程序调用时,会向该池中请求一个实例,用完之后,调用 recycle() 方法来释放该实例,从而使其可被其他模块复用。