Android:如何将枚举放入捆绑包中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3293020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:31:43  来源:igfitidea点击:

Android: How to put an Enum in a Bundle?

androidenumsandroid-bundle

提问by zer0stimulus

How do you add an Enum object to an Android Bundle?

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

回答by miguel

Enums are Serializable so there is no issue.

枚举是可序列化的,所以没有问题。

Given the following enum:

鉴于以下枚举:

enum YourEnum {
  TYPE1,
  TYPE2
}

Bundle:

捆:

// put
bundle.putSerializable("key", YourEnum.TYPE1);

// get 
YourEnum yourenum = (YourEnum) bundle.get("key");

Intent:

意图:

// put
intent.putExtra("key", yourEnum);

// get
yourEnum = (YourEnum) intent.getSerializableExtra("key");

回答by Alejandro Colorado

I know this is an old question, but I came with the same problem and I would like to share how I solved it. The key is what Miguel said: Enums are Serializable.

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

Given the following enum:

鉴于以下枚举:

enum YourEnumType {
    ENUM_KEY_1, 
    ENUM_KEY_2
}

Put:

放:

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

回答by TheIT

For completeness sake, this is a full example of how to put in and get back an enum from a bundle.

为了完整起见,这是一个完整的示例,说明如何从包中放入和取回枚举。

Given the following enum:

鉴于以下枚举:

enum EnumType{
    ENUM_VALUE_1,
    ENUM_VALUE_2
}

You can put the enum into a bundle:

您可以将枚举放入一个包中:

bundle.putSerializable("enum_key", EnumType.ENUM_VALUE_1);

And get the enum back:

并取回枚举:

EnumType enumType = (EnumType)bundle.getSerializable("enum_key");

回答by Vladislav

I use kotlin.

我使用科特林。

companion object {

        enum class Mode {
            MODE_REFERENCE,
            MODE_DOWNLOAD
        }
}

then put into Intent:

然后放入意图:

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

when you net to get value:

当您净获得价值时:

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

回答by user602359

It may be better to pass it as string from myEnumValue.name() and restore it from YourEnums.valueOf(s), as otherwise the enum's ordering must be preserved!

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

Longer explanation: Convert from enum ordinal to enum type

更详细的解释:转换从枚举顺序来枚举类型

回答by Charlie Jones

Another option:

另外一个选项:

public enum DataType implements Parcleable {
    SIMPLE, COMPLEX;

    public static final Parcelable.Creator<DataType> CREATOR = new Creator<DataType>() {

        @Override
        public DataType[] newArray(int size) {
            return new DataType[size];
        }

        @Override
        public DataType createFromParcel(Parcel source) {
            return DataType.values()[source.readInt()];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.ordinal());
    }
}

回答by Gotcha

Use bundle.putSerializable(String key, Serializable s) and bundle.getSerializable(String key):

使用 bundle.putSerializable(String key, Serializable s) 和 bundle.getSerializable(String key):

enum Mode = {
  BASIC, ADVANCED
}

Mode m = Mode.BASIC;

bundle.putSerializable("mode", m);

...

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

Documentation: http://developer.android.com/reference/android/os/Bundle.html

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

回答by Rasoul Miri

For Intentyou can use this way:

对于Intent,您可以使用这种方式:

Intent : kotlin

意图:科特林

FirstActivity :

第一活动:

val intent = Intent(context, SecondActivity::class.java)
intent.putExtra("type", typeEnum.A)
startActivity(intent)

SecondActivity:

第二个活动:

override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState) 
     //...
     val type = (intent.extras?.get("type") as? typeEnum.Type?)
}

回答by Smalls

One thing to be aware of -- if you are using bundle.putSerializablefor a Bundleto be added to a notification, you could run into the following issue:

需要注意的一件事——如果您正在使用bundle.putSerializable将 aBundle添加到通知中,您可能会遇到以下问题:

*** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
    java.lang.RuntimeException: Parcelable encountered ClassNotFoundException reading a Serializable object.

...

To get around this, you can do the following:

要解决此问题,您可以执行以下操作:

public enum MyEnum {
    TYPE_0(0),
    TYPE_1(1),
    TYPE_2(2);

    private final int code;

    private MyEnum(int code) {
        this.code = navigationOptionLabelResId;
    }

    public int getCode() {
        return code;
    }

    public static MyEnum fromCode(int code) {
        switch(code) {
            case 0:
                return TYPE_0;
            case 1:
                return TYPE_1;
            case 2:
                return TYPE_2;
            default:
                throw new RuntimeException(
                    "Illegal TYPE_0: " + code);
        }
    }
}

Which can then be used like so:

然后可以像这样使用:

// Put
Bundle bundle = new Bundle();
bundle.putInt("key", MyEnum.TYPE_0.getCode());

// Get 
MyEnum myEnum = MyEnum.fromCode(bundle.getInt("key"));

回答by m3esma

A simple way, assign integer value to enum

一个简单的方法,将整数值赋给枚举

See the following example:

请参阅以下示例:

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

}

Sender Side:

发送方:

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

Receiver Side:

接收端:

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();