Android 获取下一个或上一个 Enum

ilo*_*mbo 1 iteration enums android

我需要一种方法来获取下一个/上一个枚举。
我的问题是我无法以正常方式迭代:

for( Mode m: Mode.values() ) {
    . . .
}
Run Code Online (Sandbox Code Playgroud)

每次调用时,我都需要在方法中获取下一个枚举:
请注意,Mode是系统枚举,因此我无法定义方法,除非我创建自己的 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
        ...
    }
Run Code Online (Sandbox Code Playgroud)

kco*_*ock 5

//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];
}
Run Code Online (Sandbox Code Playgroud)

对于 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]
Run Code Online (Sandbox Code Playgroud)

然后你可以有类似的东西:

enum class MyEnum {
    ONE, TWO, THREE
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用 val two = MyEnum.ONE.next()