簡體   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