I need a way to get the next/previous enum.
My problem is that I cannot iterate the normal way:
for( Mode m: Mode.values() ) {
. . .
}
I need to get the next enum inside a method, each time it is called:
Note that Mode is a system Enum, therefore I cannot define methods, unless I create my own Enum, which is a solution, but a less preferred one.
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];
}
For Kotlin, you can declare an extension function on all enum types that would allow you to define a next()
function on all enum instances:
/**
* 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]
Then you can have something like:
enum class MyEnum {
ONE, TWO, THREE
}
Then you can just use val two = MyEnum.ONE.next()
Implement this method:
public static Mode nextMode(Mode mode) {
return (mode.ordinal() < Mode.values().length - 1) ? Mode.values()[mode.ordinal() + 1] : null;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.