将活动A中的mutableList传递给Kotlin中的活动B.

时间:2018-01-31 11:49:00

标签: android android-intent kotlin

我正试图通过Kotlin中的意图将活动 A 中的数据传递给活动 B

问题是我有videos: MutableList<Video>intent.putParcelableArrayListExtra("VIDEOS", videos)只接受ArrayList<out Parcelable>作为参数。

问题

*。如何将活动 A 中的mutableList数据发送到活动 B

*。或者我是否必须将其转换为ArrayList<Video>

PS: Video实现了Parcelable

2 个答案:

答案 0 :(得分:7)

如果你想坚持通过Intent传递它,那么将它转换为ArrayList(或者将其存储为首位?)是一个简单的解决方案。有一个ArrayList constructor以一个集合作为参数:

intent.putParcelableArrayListExtra("VIDEOS", ArrayList(videos))

答案 1 :(得分:1)

对于那些询问 Parcelable 类是如何创建的,这是我在 Kotlin 中提出的解决方案

Parcelable 类:

@Parcelize
data class ExampleModel(
        var stringOne: String,
        var stringTwo: String): Parcelable

然后在活动 A 中,您可以创建一个 ArrayList 并通过意图将其发送到活动 B

private var exampleMutableList: MutableList<ExampleModel> = arrayListOf()
exampleMutableList.add(ExampleModel("hello", "world"))
intent.putExtra("example", ArrayList(exampleMutableList))

在 Activity B 中,我们可以接收到我们的 ArrayList:

exampleMutableList = intent.getParcelableArrayListExtra<ExampleModel>("example") as ArrayList<ExampleModel>

一切顺利!

相关问题