如何将Enum对象添加到Android Bundle中?


当前回答

一种简单的方法,将整数值赋给enum

示例如下:

public enum MyEnum {

    TYPE_ONE(1), TYPE_TWO(2), TYPE_THREE(3);

    private int value;

    MyEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

}

发件人页面:

Intent nextIntent = new Intent(CurrentActivity.this, NextActivity.class);
nextIntent.putExtra("key_type", MyEnum.TYPE_ONE.getValue());
startActivity(nextIntent);

接收端:

Bundle mExtras = getIntent().getExtras();
int mType = 0;
if (mExtras != null) {
    mType = mExtras.getInt("key_type", 0);
}

/* OR
    Intent mIntent = getIntent();
    int mType = mIntent.getIntExtra("key_type", 0);
*/

if(mType == MyEnum.TYPE_ONE.getValue())
    Toast.makeText(NextActivity.this, "TypeOne", Toast.LENGTH_SHORT).show();
else if(mType == MyEnum.TYPE_TWO.getValue())
    Toast.makeText(NextActivity.this, "TypeTwo", Toast.LENGTH_SHORT).show();
else if(mType == MyEnum.TYPE_THREE.getValue())
    Toast.makeText(NextActivity.this, "TypeThree", Toast.LENGTH_SHORT).show();
else
    Toast.makeText(NextActivity.this, "Wrong Key", Toast.LENGTH_SHORT).show();

其他回答

使用包。putSerializable(String key, Serializable s)和bundle。getSerializable (String键):

enum Mode = {
  BASIC, ADVANCED
}

Mode m = Mode.BASIC;

bundle.putSerializable("mode", m);

...

Mode m;
m = bundle.getSerializable("mode");

文档:http://developer.android.com/reference/android/os/Bundle.html

我用高棉。

companion object {

        enum class Mode {
            MODE_REFERENCE,
            MODE_DOWNLOAD
        }
}

然后放入Intent:

intent.putExtra(KEY_MODE, Mode.MODE_DOWNLOAD.name)

当你上网获得价值时:

mode = Mode.valueOf(intent.getStringExtra(KEY_MODE))

我知道这是一个老问题,但我也遇到了同样的问题,我想分享一下我是如何解决它的。关键是Miguel所说的:枚举是可序列化的。

给定以下enum:

enum YourEnumType {
    ENUM_KEY_1, 
    ENUM_KEY_2
}

Put:

Bundle args = new Bundle();
args.putSerializable("arg", YourEnumType.ENUM_KEY_1);

最好从myEnumValue.name()中将其作为字符串传递,并从yourenum . valueof (s)中恢复,否则必须保留枚举的顺序!

更详细的解释:从枚举序数转换为枚举类型

enum YourEnum { 类型1, 类型2 }

传递bundle as bundleOf("TYPE" to youenum . type1)

收到, 参数?。let {it.getSerializable(B"TYPE") as YourEnum}