yas*_*sin 1 android kotlin anko
我正在将Kotlin与Anko结合使用,我想将其他玩家列表发送给另一个活动。
class Player(var name: String?) {
var score: Int = 0
init {
this.score = 0
}
}
Run Code Online (Sandbox Code Playgroud)
我的活动:
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle ? ) {
btn.setOnClickListener {
val players = ArrayList <Player> ()
players.add(Player("John"))
players.add(Player("Jeff"))
startActivity <ScoreActivity> ("key" to players)
}
}
}
Run Code Online (Sandbox Code Playgroud)
当代码到达startActivity行时,出现此错误:
java.lang.RuntimeException:包裹:无法封送值com.yasin.myapp.Player@4e3940e
我想我的班级播放器出了点问题,但是我不知道是怎么回事。我正在使用Kotlin版本1.1.4。有人可以帮我吗?
Your class should implement Parcelable (or Serializable, though Parcelable is the advised one on Android) to be able to pass the objects across Activity using the Intent.
Using Kotlin 1.1.4 and Android Extensions Plugin, you can add @Parcelize annotation to get the Parcelable implementation.
@Parcelize
class Player(var name: String?) : Parcelable {
// ...
Run Code Online (Sandbox Code Playgroud)
Refer the blog post.
This feature is covered as experimental, so you have turn on an experimental flag in your build.gradle file:
androidExtensions {
experimental = true
}
Run Code Online (Sandbox Code Playgroud)
Another option is to use this plugin to generate the boilerplate code necessary for the Parcelable implementation, but you should remember to update the implementation code everytime you change any properties in the class.
Or you can write your own Parcelable implementation.
| 归档时间: |
|
| 查看次数: |
3616 次 |
| 最近记录: |