在我的自定义对象中,我有7个属性,其中5个是字符串,并且在构造函数中可以自动生成,但其他两个不会自动生成。最后两个是Place
和ArrayList<int>
类:
class Spot() : Parcelable{
private var uid: String? = null
private var timeFrom: String? = null
private var timeTo: String? = null
private var rate: String? = null
private var description: String? = null
private var place: Place? = null
private var days : ArrayList<Int>? = null
constructor(parcel: Parcel) : this() {
uid = parcel.readString()
timeFrom = parcel.readString()
timeTo = parcel.readString()
rate = parcel.readString()
description = parcel.readString()
}
...
我如何将它们包裹?
答案 0 :(得分:0)
有几种方法可以做到这一点。您需要在constructor
和writeToParcel方法中为ArrayList和Place Object自己添加代码。
构造函数
constructor(parcel: Parcel) : this() {
uid = parcel.readString()
timeFrom = parcel.readString()
timeTo = parcel.readString()
rate = parcel.readString()
description = parcel.readString()
// Add the below to line of code
days = parcel.readArrayList(Int::class.java.classLoader) as ArrayList<Int>?
place = parcel.readParcelable<Place>(Place::class.java.classLoader)
}
writeToParcel
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(uid)
parcel.writeString(timeFrom)
parcel.writeString(timeTo)
parcel.writeString(rate)
parcel.writeString(description)
// Add the below to line of code
parcel.writeList(days)
parcel.writeParcelable(place, flags)
}
如果我没记错的话,Google的Place类已经是Parcelable了,因此此代码应该可以使用。
希望有帮助!