我有一个类,它有一个 ArrayList<>
类型的成员变量.这两个类都实现了 parcelable。我一直在思考如何完成引用了其他类(class)的类(class)。
这是我的:
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
类(class)。我觉得这个还行:
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)
}
关于android - 可使用自定义可打包对象进行打包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45986247/