376

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

4

13 回答 13

802

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

给定以下枚举:

enum YourEnum {
  TYPE1,
  TYPE2
}

捆:

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

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

意图:

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

// get
yourEnum = (YourEnum) intent.getSerializableExtra("key");
于 2011-03-15T09:48:30.133 回答
170

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

给定以下枚举:

enum YourEnumType {
    ENUM_KEY_1, 
    ENUM_KEY_2
}

放:

Bundle args = new Bundle();
args.putSerializable("arg", YourEnumType.ENUM_KEY_1);
于 2012-08-09T11:28:31.593 回答
45

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

给定以下枚举:

enum EnumType{
    ENUM_VALUE_1,
    ENUM_VALUE_2
}

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

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

并取回枚举:

EnumType enumType = (EnumType)bundle.getSerializable("enum_key");
于 2014-03-05T03:11:04.437 回答
34

我使用科特林。

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))
于 2016-12-01T12:41:53.087 回答
17

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!

Longer explanation: Convert from enum ordinal to enum type

于 2011-02-15T18:23:53.583 回答
6

另外的选择:

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());
    }
}
于 2014-06-25T15:19:38.913 回答
3

在科特林:

enum class MyEnum {
  NAME, SURNAME, GENDER
}

将此枚举放入捆绑包中:

Bundle().apply {
  putInt(MY_ENUM_KEY, MyEnum.ordinal)
}

从 Bundle 中获取枚举:

val ordinal = getInt(MY_ENUM_KEY, 0)
MyEnum.values()[ordinal]

完整示例:

class MyFragment : Fragment() {

    enum class MyEnum {
        NAME, SURNAME, GENDER
    }

    companion object {
        private const val MY_ENUM_KEY = "my_enum_key"

        fun newInstance(myEnum: MyEnum) = MyFragment().apply {
            arguments = Bundle().apply {
                putInt(MY_ENUM_KEY, myEnum.ordinal)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(requireArguments()) {
            val ordinal = getInt(MY_ENUM_KEY, 0)
            val myEnum = MyEnum.values()[ordinal]
        }
    }
}

在 Java 中:

public final class MyFragment extends Fragment {
    private static final String MY_ENUM_KEY = "my_enum";

    public enum MyEnum {
        NAME,
        SURNAME,
        GENDER
    }

    public final MyFragment newInstance(MyEnum myEnum) {
        Bundle bundle = new Bundle();
        bundle.putInt(MY_ENUM_KEY, myEnum.ordinal());
        MyFragment fragment = new MyFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = this.requireArguments();
        int ordinal = arguments.getInt(MY_ENUM_KEY, 0);
        MyEnum myEnum = MyEnum.values()[ordinal];
    }
}
于 2021-08-13T13:28:40.397 回答
2

使用 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");

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

于 2015-03-28T16:56:42.633 回答
2

我创建了一个 Koltin 扩展:

fun Bundle.putEnum(key: String, enum: Enum<*>) {
    this.putString( key , enum.name )
}

inline fun <reified T: Enum<T>> Intent.getEnumExtra(key:String) : T {
    return enumValueOf( getStringExtra(key) )
}

创建一个包并添加:

Bundle().also {
   it.putEnum( "KEY" , ENUM_CLAS.ITEM )
}

并得到:

intent?.getEnumExtra< ENUM_CLAS >( "KEY" )?.let{}

于 2020-04-21T15:09:19.313 回答
1

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

意图:科特林

第一活动:

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

第二活动:

override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState) 
     //...
     val type = (intent.extras?.get("type") as? typeEnum.Type?)
}
于 2018-11-03T13:46:40.210 回答
0

需要注意的一件事 - 如果您使用bundle.putSerializableaBundle添加到通知中,您可能会遇到以下问题:

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

...

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

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

然后可以像这样使用它:

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

// Get 
MyEnum myEnum = MyEnum.fromCode(bundle.getInt("key"));
于 2017-11-06T18:43:55.793 回答
-1

我认为将 enum 转换为 int (对于普通枚举)然后在 bundle 上设置是最简单的方法。像这样的意图代码:

myIntent.PutExtra("Side", (int)PageType.Fornt);

然后检查状态:

int type = Intent.GetIntExtra("Side",-1);
if(type == (int)PageType.Fornt)
{
    //To Do
}

但不适用于所有枚举类型!

于 2016-08-17T07:43:28.203 回答
-1

一种简单的方法,将整数值分配给枚举

请参见以下示例:

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();
于 2016-08-04T10:22:04.377 回答