使用具有 Parcelable 的枚举

/**
 * Created by Nick Cardoso on 03/08/16.
 * This is not a complete parcelable implementation, it only highlights the easiest 
 * way to read and write your Enum values to your parcel
 */
public class Foo implements Parcelable {

    private final MyEnum myEnumVariable;
    private final MyEnum mySaferEnumVariableExample;

    public Foo(Parcel in) {

        //the simplest way
        myEnumVariable = MyEnum.valueOf( in.readString() );

        //with some error checking
        try {
            mySaferEnumVariableExample= MyEnum.valueOf( in.readString() );
        } catch (IllegalArgumentException e) { //bad string or null value
            mySaferEnumVariableExample= MyEnum.DEFAULT;
        }

    }
    
    ...

    @Override
    public void writeToParcel(Parcel dest, int flags) {

        //the simple way
        dest.writeString(myEnumVariable.name()); 

        //avoiding NPEs with some error checking
        dest.writeString(mySaferEnumVariableExample == null? null : mySaferEnumVariableExample.name());

    }
    
}

public enum MyEnum {
    VALUE_1,
    VALUE_2,
    DEFAULT
}

这比(例如)使用序数更可取,因为在枚举中插入新值不会影响以前存储的值