【问题标题】:Pass a mutableList from activity A to activity B in Kotlin.将一个 mutableList 从活动 A 传递到 Kotlin 中的活动 B。
【发布时间】:2018-07-10 12:29:42
【问题描述】:

我正在尝试通过 Kotlin 中的意图将数据从活动 A 传递到活动 B

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

问题

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

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

PS: Videoimplements Parcelable

【问题讨论】:

    标签: android android-intent kotlin


    【解决方案1】:

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

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

    【讨论】:

    • 当这个数组得到时,第二个活动应该如何表现?因为似乎当我们使用 "getParcelableArrayListExtra" 时,它会出错
    【解决方案2】:

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

    Parcelable 类:

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

    然后在 Activity A 中,您可以创建一个 ArrayList 并通过 Intent 将其发送到 Activity B

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

    在活动 B 中,我们可以收到我们的 ArrayList:

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

    一切顺利!

    【讨论】:

    • 这是一个非常完整的答案。应该接受一个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多