如何通过Kotlin中的Intent传递自定义对象 [英] How to Pass custom object via intent in kotlin
本文介绍了如何通过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
这篇关于如何通过Kotlin中的Intent传递自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文