How to read and write Enum into parcel on Android?

后端 未结 6 742
旧时难觅i
旧时难觅i 2021-02-01 12:18

Here is my model class:

public enum Action {
    RETRY, SETTINGS
}

private int imageId;
private String description;
private String actionName;
private Action ac         


        
6条回答
  •  悲&欢浪女
    2021-02-01 13:06

    One way to do this is to write Actions in integer and read them properly as integer and convert them into Action. What I mean:

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.imageId);
        dest.writeString(this.description);
        dest.writeString(this.actionName);
    
        int actionAsInt = action == Action.RETRY ? 1 : 0;
        dest.writeInt(actionAsInt);
    }
    
    protected NetworkError(Parcel in) {
        this.imageId = in.readInt();
        this.description = in.readString();
        this.actionName = in.readString();
    
        int actionAsInt = in.readInt();
        this.action = actionAsInt == 1 ? Action.RETRY : Action.SETTINGS;
    }
    

    Try it. Success ...

提交回复
热议问题