可自定义parcelable对象

我有一个具有类型ArrayList<>的成员变量的类。 这两个类实现parcelable。 我被困在如何完成对其他类的引用的类。

这是我有什么:

 data class Tab (val name: String, val title: String, val color: String, val sections: ArrayList<Section>) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), parcel.readString(), parcel.readString(), parcel.readTypedList<Section>(sections, Section.CREATOR)) override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeString(name) dest?.writeString(title) dest?.writeString(color) dest?.writeTypedList<Section>(sections) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<Tab> { override fun createFromParcel(parcel: Parcel): Tab { return Tab(parcel) } override fun newArray(size: Int): Array<Tab?> { return arrayOfNulls(size) } } } 

注意这个类如何有一个名为sections的值,它是一个ArrayList<Section> 。 我需要将该变量写入一个parcelable,但它不工作。

作为参考,这里是Section类。 我认为这一个是确定的:

 data class Section(val type: String, val text: String, val imageName: String) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), parcel.readString(), parcel.readString()) override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeString(type) dest?.writeString(text) dest?.writeString(imageName) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<Section> { override fun createFromParcel(parcel: Parcel): Section { return Section(parcel) } override fun newArray(size: Int): Array<Section?> { return arrayOfNulls(size) } } } 

它是失败的readTypedList和writeTypedList行。

感谢您的帮助。

首先解决方案

 @Suppress("UNCHECKED_CAST") constructor(parcel: Parcel): this(parcel.readString(), parcel.readString(), parcel.readString(), parcel.readArrayList(Tab::class.java.classLoader) as ArrayList<Section>) 

第二种方案

 constructor(parcel: Parcel): this(parcel.readString(), parcel.readString(), parcel.readString(), ArrayList<Section>()){ parcel.readTypedList(sections, Section.CREATOR) }