枚举类实现Parcelable的写法如下:
public enum MyEnum implements Parcelable {
FIRST(1), SECOND(2);
private int mValue;
MyEnum(int value) {
this.mValue = value;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mValue);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<MyEnum> CREATOR = new Creator<MyEnum>() {
@Override
public MyEnum createFromParcel(Parcel in) {
return MyEnum.values()[in.readInt()];
}
@Override
public MyEnum[] newArray(int size) {
return new MyEnum[size];
}
};
}
当枚举类为一个类的成员变量,并且该类也要实现Parcelable接口时,则先让枚举类实现Parcelable接口,
public class MyClass implements Parcelable {
private String name;
private int age;
private MyEnum myEnum;
protected MyClass(Parcel in) {
name = in.readString();
age = in.readInt();
myEnum = in.readParcelable(MyEnum.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
dest.writeParcelable(myEnum, flags);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<MyClass> CREATOR = new Creator<MyClass>() {
@Override
public MyClass createFromParcel(Parcel in) {
return new MyClass(in);
}
@Override
public MyClass[] newArray(int size) {
return new MyClass[size];
}
};
}