*** 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"));
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?)
}
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];
}
}
enum class MyEnum {
FOO,
BAR
}
val bundle = Bundle()
bundle.putAll(bundleOf("myKey", MyEnum.FOO))
// to read
val myEnum = bundle.get("myKey") as MyEnumClass