繁体   English   中英

Android获取下一个或上一个枚举

[英]Android Get the next or previous Enum

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

for( Mode m: Mode.values() ) {
    . . .
}

我需要在每次调用方法时获取方法中的下一个枚举:
请注意, Mode是一个系统枚举,因此,除非创建自己的枚举(这是一种解决方案,但不是首选的枚举),否则无法定义方法。

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

实现此方法:

public static Mode nextMode(Mode mode) {
    return (mode.ordinal() < Mode.values().length - 1) ? Mode.values()[mode.ordinal() + 1] : null;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM