How to read and write Enum into parcel on Android?

后端 未结 6 746
旧时难觅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:01

    Sample Kotlin-Code (null-safe):

    writeInt(action?.ordinal ?: -1)
    
    action = readInt().let { if (it >= 0) enumValues()[it] else null }
    

    Which can be encapsulated in a write/readEnum Methods as extensions to Parcel:

    fun > Parcel.writeEnum(value: T?) = 
        writeInt(value?.ordinal ?: -1)
    
    inline fun > Parcel.readEnum(): T? = 
        readInt().let { if (it >= 0) enumValues()[it] else null }
    

提交回复
热议问题