//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()