似乎没有一种从属性枚举中获取Java枚举的自动方法 - 在Java中,您可以获得指定的数值 - 该字符串用于XML文件(如您所示)。
您可以在视图构造函数中执行此操作:
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.IconView,
0, 0);
// Gets you the 'value' number - 0 or 666 in your example
if (a.hasValue(R.styleable.IconView_icon)) {
int value = a.getInt(R.styleable.IconView_icon, 0));
}
a.recycle();
}
如果你想将值放入枚举中,你需要自己将值映射到Java枚举中,例如:
private enum Format {
enum_name_one(0), enum_name_n(666);
int id;
Format(int id) {
this.id = id;
}
static Format fromId(int id) {
for (Format f : values()) {
if (f.id == id) return f;
}
throw new IllegalArgumentException();
}
}
然后在第一个代码块中,您可以使用:
Format format = Format.fromId(a.getInt(R.styleable.IconView_icon, 0)));
(虽然此时抛出异常可能不是一个好主意,可能最好选择合理的默认值)