简体   繁体   中英

How can I parce a List<Int> in Kotlin?

I'm trying to parce a list of Int.

I've tried this solution: How to parcel List<Int> with kotlin , but not worked

data class Pizza(
   var ingredients: ArrayList<Int>,
   val name: String,
   val imageUrl: String
) : Parcelable {
constructor(parcel: Parcel) : this(
        TODO("ingredients"),
        parcel.readString(),
        parcel.readString()) {
}

override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(name)
    parcel.writeString(imageUrl)
}

override fun describeContents(): Int {
    return 0
}

companion object CREATOR : Parcelable.Creator<Pizza> {
    override fun createFromParcel(parcel: Parcel): Pizza {
        return Pizza(parcel)
    }

    override fun newArray(size: Int): Array<Pizza?> {
        return arrayOfNulls(size)
    }
}

Why don't you just try @Parcelize ! Another cool feature of Kotlin.

Enable kotlin experimental in gradle

//Make sure you have adeed 
apply plugin: ‘kotlin-android-extensions’

androidExtensions {
    experimental = true
}

Then

@Parcelize
data class Pizza(
   var ingredients: ArrayList<Int>,
   val name: String,
   val imageUrl: String
) : Parcelable

Thats it.

There are several ways to write/read a list to/from a parcel, here is a simple solution.

First, use writeList to write a list into a parcel

override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeList(ingredients)
    parcel.writeString(name)
    parcel.writeString(imageUrl)
}

Then, use readArrayList to read the list from the parcel.

constructor(parcel: Parcel) : this (
    parcel.readArrayList(Int::class.java.classLoader) as ArrayList<Int>,
    parcel.readString(),
    parcel.readString()
)

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM