我创建了一个带有枚举类型的声明样式属性的自定义视图(查找它为here)。在xml中,我现在可以为我的自定义属性选择一个枚举条目。现在我想创建一个以编程方式设置此值的方法,但我不能访问枚举。
attr.xml
<declare-styleable name="IconView">
<attr name="icon" format="enum">
<enum name="enum_name_one" value="0"/>
....
<enum name="enum_name_n" value="666"/>
</attr>
</declare-styleable>
layout.xml
<com.xyz.views.IconView
android:id="@+id/heart_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:icon="enum_name_x"/>
我需要的是:mCustomView.setIcon(R.id.enum_name_x);
,但是我找不到枚举,或者我甚至不知道如何获得枚举或枚举的名称。
发布于 2013-09-25 04:58:15
似乎没有一种自动的方法从属性枚举中获取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)));
(尽管在这一点上抛出异常可能不是一个好主意,但最好选择一个合理的默认值)
发布于 2019-01-24 15:51:18
这很简单,让我们向每个人展示一个例子,只是为了说明它是多么容易:
attr.xml:
<declare-styleable name="MyMotionLayout">
<attr name="motionOrientation" format="enum">
<enum name="RIGHT_TO_LEFT" value="0"/>
<enum name="LEFT_TO_RIGHT" value="1"/>
<enum name="TOP_TO_BOTTOM" value="2"/>
<enum name="BOTTOM_TO_TOP" value="3"/>
</attr>
</declare-styleable>
自定义布局:
public enum Direction {RIGHT_TO_LEFT, LEFT_TO_RIGHT, TOP_TO_BOTTOM, BOTTOM_TO_TOP}
Direction direction;
...
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.MyMotionLayout);
Direction direction = Direction.values()[ta.getInt(R.styleable.MyMotionLayout_motionOrientation,0)];
现在像使用任何其他枚举变量一样使用方向。
发布于 2019-11-12 17:26:57
让我添加一个用kotlin编写的解决方案。添加内联扩展函数:
inline fun <reified T : Enum<T>> TypedArray.getEnum(index: Int, default: T) =
getInt(index, -1).let { if (it >= 0) enumValues<T>()[it] else default
}
现在获取枚举很简单:
val a: TypedArray = obtainStyledAttributes(...)
val yourEnum: YourEnum = a.getEnum(R.styleable.YourView_someAttr, YourEnum.DEFAULT)
a.recycle()
https://stackoverflow.com/questions/18382559
复制相似问题