Android:自定义控件 --- 自定义属性 枚举值(固定属性值)

时间:2021-08-05 20:38:36

今天写一个自定义控件,为了提高使用者使用效率,需要对一个属性的所有可能属性值进行枚举(即,只能选择使用给出的属性值)

查了很多资料,自己总结一下。


如何写自定义控件就不在赘述了,网上很多大神写的都很好,此处只说明这一种情况。

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="custom_view">
<attr name="checkType" format="string" />
<attr name="type">
<enum name="password" value="1" />
<enum name="checkButton" value="2" />
<enum name="phone" value="3" />
</attr>
</declare-styleable>
</resources>

其中,一般属性需要指定 name 和 format 

枚举属性只需指定 name

然后用 enum 标签 指定所有可能属性的 name和value(注:value只能为int型)


class中取属性值

int type = array.getInt(R.styleable.custom_view_type, 0);

此处取值为int


这样就实现了,当开发者用此控件时,type属性,只能使用这里给出的3个属性值。