Android获取下一个或上一个枚举
我需要一种方法来获取下一个/上一个枚举。Android获取下一个或上一个枚举,android,enums,iteration,Android,Enums,Iteration,我需要一种方法来获取下一个/上一个枚举。 我的问题是我无法以正常方式迭代: for( Mode m: Mode.values() ) { . . . } 每次调用一个方法时,我都需要获取该方法中的下一个枚举: 请注意,模式是一个系统枚举,因此我无法定义方法,除非我创建自己的枚举,这是一个解决方案,但不是首选方案 public class A { private Mode m; A() { m = Mode.CLEAR; } ...
我的问题是我无法以正常方式迭代:
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
...
}
公共A类{
私有模式m;
(){
m=模式。清除;
}
...
受保护的onClick(视图v){
...
v、 getBackground().SetColorFilter(R.color.azure,m);
m=m.next();//
对于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]
然后您可以使用val two=MyEnum.ONE.next()
对于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]
然后您可以使用val two=MyEnum.ONE.next()
实现此方法:
public static Mode nextMode(Mode mode) {
return (mode.ordinal() < Mode.values().length - 1) ? Mode.values()[mode.ordinal() + 1] : null;
}
公共静态模式下一个模式(模式){
返回(mode.ordinal()
实施此方法:
public static Mode nextMode(Mode mode) {
return (mode.ordinal() < Mode.values().length - 1) ? Mode.values()[mode.ordinal() + 1] : null;
}
公共静态模式下一个模式(模式){
返回(mode.ordinal()
您确定ordinal()获得值中的顺序吗?我知道ordinal()给出了枚举定义中写入的枚举顺序,但我不确定values()是否有界返回相同的枚举顺序。您确定ordinal()获得值中的顺序吗?我知道ordinal()给出枚举在枚举定义中写入时的顺序,我不确定values()是否有界返回相同的枚举顺序。