LoginSignup
3
4

More than 5 years have passed since last update.

[Android] Enum に Parcelable インタフェースを実装するコード

Posted at

Android Architecture Components の Navigation の引数に Enum を渡したかったのですが、現状(2018/8/22)の最新バージョン(1.0.0-alpha04)では Serializable に対応していなかったので。

下記の HogeType を任意の名称に変更してください。またこの例は、Enum の付加情報としてリソースID(resId)を付け加えています。HogeType.HOGE1.resIdhogeType.resId でリソースID を取り出せます。

enum class HogeType(val resId: Int) : Parcelable {
    HOGE1(R.string.text_hoge1),
    HOGE2(R.string.text_hoge2),
    ;

    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeInt(ordinal)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object {
        @JvmField
        val CREATOR: Parcelable.Creator<HogeType> = object : Parcelable.Creator<HogeType> {
            override fun createFromParcel(`in`: Parcel): HogeType {
                return HogeType.values()[`in`.readInt()]
            }

            override fun newArray(size: Int): Array<HogeType?> {
                return arrayOfNulls(size)
            }
        }
    }
}
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4