我有一个实现Parcelable
的数据类,它的所有字段都保存到Parcel
中,除了构造函数外的一个变量。
我的班级:
data class MyParcelableClass(
val fieldA: String,
val fieldB: Int,
val fieldC: AnotherParcelableClass
) : Parcelable {
// This is the one I'm having problems with
var troublesomeVariable: TroublesomeParcelableClass? = null
set(value) {
field = value
if (field != null)
// do stuff (irrelevant to the question)
}
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.run {
writeString(fieldA)
writeInt(fieldB)
writeParcelable(fieldC, flags)
writeParcelable(troublesomeVariable, flags)
/*
* At this point, troublesomeVariable is null,
* even though a value has already been assigned
*/
}
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<MyParcelableClass> {
override fun createFromParcel(source: Parcel): MyParcelableClass {
val fieldA = source.readString()!!
val fieldB = source.readInt()
val fieldC = source.readParcelable<AnotherParcelableClass>(AnotherParcelableClass::class.java.classLoader)!!
val troublesomeVariable = source.readParcelable<TroublesomeParcelableClass>(TroublesomeParcelableClass::class.java.classLoader)!!
/*
* Since troublesomeVariable has been written as null to the parcel,
* it will obviously be null here as well
*/
return MyParcelableClass(fieldA, fieldB, fieldC).also {
it.troublesomeVariable = troublesomeVariable
}
}
override fun newArray(size: Int): Array<MyParcelableClass?> = arrayOfNulls(size)
}
}
正如代码中的注释所显示的那样,问题是变量已经被写入包为null,尽管它已经指定了一个值--我放置了大量日志和断点,以确保变量在解析之前不是空的,而且实际上不是空的。
因此,总之,我想知道我需要做什么,才能成功地将变量写入包裹,然后像其他人一样检索它。任何帮助都将不胜感激。
发布于 2019-09-13 00:36:23
Kotlin的数据类具有与Java的POJO相同的行为:初始化构造函数中的所有字段,并有getter(和setter,视需要而定)。
当数据类实现Parcelable
时,实际上只有构造函数中包含的字段被写入并从Parcel
中读取--我通过使用@Parcelize
注释而不是手动实现实现了它,并且IDE显示了一个提示,告诉我如何用@IgnoredOnParcel
注释troublesomeVariable
。
因此,解决方案是将troublesomeVariable
作为一个private var
包含在构造函数中,并手动实现它的getter和setter,就像在Java中一样,它工作正常。
https://stackoverflow.com/questions/57912352
复制相似问题