1

次/前の列挙型を取得する方法が必要です。
私の問題は、通常の方法で反復できないことです:

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

メソッドが呼び出されるたびに、メソッド内の次の列挙型を取得する必要があり
ます。モードはシステム列挙型であるため、独自の列挙型を作成しない限り、メソッドを定義できません。これはソリューションですが、あまり優先されません。

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
        ...
    }
4

2 に答える 2

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];
}

next()Kotlin の場合、すべての enum インスタンスで関数を定義できるようにするすべての enum 型で拡張関数を宣言できます。

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

于 2013-02-22T06:53:59.603 に答える
4

このメソッドを実装します。

public static Mode nextMode(Mode mode) {
    return (mode.ordinal() < Mode.values().length - 1) ? Mode.values()[mode.ordinal() + 1] : null;
}
于 2013-02-22T07:00:51.780 に答える