0

我有一个可变列表:

var books = mutableListOf<Book>()

模型“书”是:

data class Book(val title: String, val id: Int)

我的代码是:

      button2.setOnClickListener{
        val delFragment = DelFragment()
        val booksforDel = Bundle()
        booksforDel.putStringArrayList("books", books as ArrayList<String>)
        delFragment.setArguments(booksforDel)

        val manager = supportFragmentManager
        delFragment.show(manager,"Delete Book")
    }

在片段中我尝试获取数据:

val booksForDelete = getArguments()?.getStringArrayList("books")!!

并得到错误:

java.lang.ArrayStoreException:com.example.http_example.model.Book 类型的源 [0] 无法存储在 java.lang.String [] 类型的目标数组中

如何将 mutableList“书”中的数据发送到 DialogFragment 中的 Bundle?

4

1 回答 1

0

您可以实现Parcelable接口:

data class Book(val title: String, val id: Int) : Parcelable {
    constructor(source: Parcel) : this(
            source.readString()!!,
            source.readInt()
    )

    override fun describeContents() = 0

    override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
        writeString(title)
        writeInt(id)
    }

    companion object {
        @JvmField
        val CREATOR: Parcelable.Creator<Book> = object : Parcelable.Creator<Book> {
            override fun createFromParcel(source: Parcel): Book = Book(source)
            override fun newArray(size: Int): Array<Book?> = arrayOfNulls(size)
        }
    }
}

并像下面这样使用它:

var books = mutableListOf<Book>()
val booksforDel = Bundle()
booksforDel.putParcelableArray("books", books.toTypedArray())

Ann 在片段中检索书籍:

val booksForDelete = arguments?.getParcelableArray("books")
于 2020-07-13T06:59:04.317 回答