我需要一种方法来获得下一个/上一个枚举 我的问题是我无法正常迭代:
for( Mode m: Mode.values() ) {
. . .
}
每次调用方法时,我需要在方法中获取下一个枚举:
请注意,模式是一个系统枚举,因此我无法定义方法,除非我创建自己的Enum,这是一个解决方案,但不太喜欢。
public class A {
private Mode m;
A() {
m = Mode.CLEAR;
}
...
protected onClick(View v) {
...
v.getBackground().SetColorFilter(R.color.azure, m);
m = m.next(); // <-- I need something like this
...
}
答案 0 :(得分:4)
//Store these somewhere in your class
Mode[] modes = Mode.values();
int modeCount = modes.length;
protected void onClick(View v) {
//Get the next mode, wrapping around if you reach the end
int nextModeOrdinal = (m.ordinal() + 1) % modeCount;
m = modes[nextModeOrdinal];
}
对于Kotlin,您可以在所有枚举类型上声明一个扩展函数,允许您在所有枚举实例上定义next()
函数:
/**
* Returns the next enum value as declared in the class. If this is the last enum declared,
this will wrap around to return the first declared enum.
*
* @param values an optional array of enum values to be used; this can be used in order to
* cache access to the values() array of the enum type and reduce allocations if this is
* called frequently.
*/
inline fun <reified T : Enum<T>> Enum<T>.next(values: Array<T> = enumValues()) =
values[(ordinal + 1) % values.size]
然后你可以有类似的东西:
enum class MyEnum {
ONE, TWO, THREE
}
然后你可以使用val two = MyEnum.ONE.next()
答案 1 :(得分:4)
实施此方法:
public static Mode nextMode(Mode mode) {
return (mode.ordinal() < Mode.values().length - 1) ? Mode.values()[mode.ordinal() + 1] : null;
}