我有一个可变的LIst:
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")
}
在Fragment中,我试图获取数据:
val booksForDelete = getArguments()?.getStringArrayList("books")!!
并得到错误:
java.lang.ArrayStoreException:com.example.http_example.model.Book类型的源[0]无法存储在java.lang.String[]类型的目标数组中
如何从mutableList发送数据"书籍";在DialogFragment中绑定?
您可以实现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())
安在一个片段中检索书籍:
val booksForDelete = arguments?.getParcelableArray("books")