如何制作RealmList< String>可包裹的? [英] How to make RealmList<String> Parcelable?

查看:62
本文介绍了如何制作RealmList< String>可包裹的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Parcelize open class TestClass(
        @SerialName("title")   
        var title: String,
        @SerialName("list")   
        var list: RealmList<String>    
) : RealmObject() { ... }

如何在此实现中打包"list"变量?
它说,即使我添加@RawValue,也无法打包这种类型的值.
这里有什么选择?一个带有解释的例子将是完美无缺的.

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.

推荐答案

类似于此方法,你可以做

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)
        }
    }
}

那你就可以做

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)
    }
}

现在您可以做

@Parcelize 
open class TestClass(
        @SerialName("title")   
        var title: String = "",
        @SerialName("list")   
        var list: @WriteWith<StringRealmListParceler> RealmList<String>? = null
) : RealmObject(), Parcelable { ... }

这篇关于如何制作RealmList&lt; String&gt;可包裹的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆