android - 如何通过 kotlin 中的 Intent 传递自定义对象

fun launchNextScreen(context: Context, people: People): Intent {
    val intent = Intent(context, NextScreenActivity::class.java)
    intent.putExtra(EXTRA_PEOPLE, (Parcelable) people)
    //intent.putExtra(EXTRA_PEOPLE, people as Parcelable)
    //intent.putExtra(EXTRA_PEOPLE, people)
    // tried above all three ways
    return intent
}

我尝试使用上面的代码使用 kotlin 通过 Intent 传递 People 类的实例,但出现错误。 我做错了什么?

最佳答案

首先,确保 People 类实现了 Serializable 接口(interface):

class People : Serializable {
    // your stuff
}

People类的内部字段也必须实现Serializable接口(interface),否则会出现运行时错误。

那么它应该可以工作了:

fun launchNextScreen(context: Context, people: People): Intent {
    val intent = Intent(context, NextScreenActivity::class.java)
    intent.putExtra(EXTRA_PEOPLE, people)
    return intent
}

要从 Intent 接收人员,您需要调用:

val people = intent.getSerializableExtra(EXTRA_PEOPLE) as? People

https://stackoverflow.com/questions/47593205/

相关文章:

android - 在 Android Studio 中创建 Kotlin 库

lambda - 在 lambda 中使用 return?

android - 使用 Kotlin for Android 进行数据绑定(bind)的问题

types - Kotlin:从列表(或其他功能转换)中消除空值

android - 在 Kotlin 中将接口(interface)作为参数传递

android - 在 Kotlin 中使用 Gson 解析 JSON 数组

kotlin - 从 java 中调用作为 java 中关键字的 kotlin 函数?

android - 在 ConstraintLayout 中使用 group 来监听多个 View

android - 如何在 androidTest 范围内使用 kapt

intellij-idea - Kotlin - IntelliJ 项目设置