繁体   English   中英

有没有办法在 Android savedInstanceState Bundle 中使用 Kotlinx 序列化?

[英]Is there a way to use Kotlinx serialisation in an Android savedInstanceState Bundle?

看起来编译器不想在putSerializablegetSerializable中使用 Kotlinx 序列化类。 它说Type mismatch: inferred type is MyViewModel.SavedState but Serializable? was expected Type mismatch: inferred type is MyViewModel.SavedState but Serializable? was expected

在我的活动中:

override fun onCreate(savedInstanceState: Bundle?) {
    AndroidInjection.inject(this)
    super.onCreate(savedInstanceState)

    setContentView(R.layout.my_activity_layout)

    viewModel.init(savedInstanceState?.getSerializable(SAVE_STATE) as? SavedState) // compiler complains here
}

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putSerializable(SAVE_STATE, viewModel.buildSaveState()) // and here
}

在我的视图模型中:

fun buildSaveState(): SavedState =
        SavedState(value1, value2, value3, value4)

@Serializable
data class SavedState(val foo: Boolean?,
                      val foo1: Enum1?,
                      val foo2: Enum2?,
                      val foo3: MyType?)

我的风格:

@Serializable
sealed class MyType {
    data class MyType1(val foo4: Enum3) : MyType()
    data class MyType2(val foo5: Enum4) : MyType()

    enum class Enum3 {
        ...
    }

    enum class Enum4 {
        ...
    }
}

我很确定 Kotlinx.Serialization 与 Bundle 的 putSerializable 不兼容 OOB。 但是,您可以将SavedState stringify ,通过putString将其发送,然后在接收端将字符串反序列化回 class。

您可以使用 kotlin-parcelize 插件( https://developer.android.com/kotlin/parcelize

首先将插件添加到您的 app/build.gradle:

plugins {
    ..
    id 'kotlin-parcelize'
}

然后将@Parcelize 注解和 Parcelable 接口添加到 class 中:

import kotlinx.parcelize.Parcelize

@Parcelize
class User(val firstName: String, val lastName: String, val age: Int): Parcelable

然后您可以将实例添加到捆绑包中:

val user = User("John", "Doe", 33)
bundle.putParcelable("mykey", user)

但是,kotlin-parcelize 插件似乎不适用于密封类,因此它可能不是您用例的正确解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM