问题
@Parcelize open class TestClass(
@SerialName("title")
var title: String,
@SerialName("list")
var list: RealmList<String>
) : RealmObject() { ... }
How can I parcelize "list"
variable in this implementation?
It says, that it's not possible to parcel this type of value even if I add @RawValue
.
What's the alternative here? An example with explanation would be flawless.
回答1:
Similarly to this approach, you can do
fun Parcel.readStringRealmList(): RealmList<String>? = when {
readInt() > 0 -> RealmList<String>().also { list ->
repeat(readInt()) {
list.add(readString())
}
}
else -> null
}
fun Parcel.writeStringRealmList(realmList: RealmList<String>?) {
writeInt(when {
realmList == null -> 0
else -> 1
})
if (realmList != null) {
writeInt(realmList.size)
for (t in realmList) {
writeString(t)
}
}
}
Then you can do
object StringRealmListParceler: Parceler<RealmList<String>?> {
override fun create(parcel: Parcel): RealmList<String>? = parcel.readStringRealmList()
override fun RealmList<String>?.write(parcel: Parcel, flags: Int) {
parcel.writeStringRealmList(this)
}
}
Now you can do
@Parcelize
open class TestClass(
@SerialName("title")
var title: String = "",
@SerialName("list")
var list: @WriteWith<StringRealmListParceler> RealmList<String>? = null
) : RealmObject(), Parcelable { ... }
来源:https://stackoverflow.com/questions/51834124/how-to-make-realmliststring-parcelable