如何在Android上读写Enum进入包裹?

这是我的模特class:

public enum Action { RETRY, SETTINGS } private int imageId; private String description; private String actionName; private Action action; public NetworkError(int imageId, String description, String actionName, Action action ) { this.imageId = imageId; this.description = description; this.actionName = actionName; this.action = action; } public int getImageId() { return imageId; } public void setImageId(int imageId) { this.imageId = imageId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getActionName() { return actionName; } public void setActionName(String actionName) { this.actionName = actionName; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.imageId); dest.writeString(this.description); dest.writeString(this.actionName); } protected NetworkError(Parcel in) { this.imageId = in.readInt(); this.description = in.readString(); this.actionName = in.readString(); } public static final Parcelable.Creator<NetworkError> CREATOR = new Parcelable.Creator<NetworkError>() { @Override public NetworkError createFromParcel(Parcel source) { return new NetworkError(source); } @Override public NetworkError[] newArray(int size) { return new NetworkError[size]; } }; 

Solutions Collecting From Web of "如何在Android上读写Enum进入包裹?"

我有类似的问题,我的解决scheme是:

 parcel.writeString(this.questionType.name()); 

和阅读:

 this.questionType = QuestionType.valueOf(parcel.readString()); 

QuestionType是枚举,记住元素的sorting很重要。

任何enum都是可序列化的。

你可以在writeToParcel()做到这一点: dest.writeSerializable(action)

而在构造函数中: action = (Action) in.readSerializable()

枚举decleration:

 public enum Action { NEXT(1), OK(2); private int action; Action(int action) { this.action = action; } } 

从包裹中读取:

 protected ActionParcel(Parcel in) { int actionTmp = in.readInt(); action = Tutorials.Action.values()[actionTmp]; } 

写入包裹:

 public void writeToParcel(Parcel dest, int flags) { int actionTmp = action == null ? -1 : action.ordinal(); dest.writeInt(actionTmp); }