如何通过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通过意图传递People类的实例,但出现错误. 我在做什么错了?

I tried the above code to pass an instance of the People class via intent using kotlin, but I am getting an error. What am I doing wrong?

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

First, make sure the People class implements the Serializable interface:

class People : Serializable {
    // your stuff
}

People类的内部字段还必须实现Serializable接口,否则会出现运行时错误.

Inner fields of People class must also implement the Serializable interface, otherwise you'll get runtime error.

然后它应该工作:

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

要接收来自Intent的人,您需要致电:

To receive people back from Intent you'll need to call:

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