我有一些 Activity ,我使用Intent在它们之间传递数据。我想从第一个 Activity 中传递我的自定义对象的数组,并在第二个 Activity 中使其成为arraylist。我拥有的代码是:
data class Attachment(val Name: String, val Content: String)
class ActivityA {
private var attachments: Array<Attachment> = arrayOf()
fun callB() {
intent = Intent(this,ActivityB::class.java).apply {
putExtra("Attachments", attachments)
}
}
}
class ActivityB {
private var attachments: ArrayList<Attachment>?
override fun onCreate(savedInstanceState: Bundle?) {
// How do I get the passed array and store in the arraylist here ?
val a: Array<Attachment> = intent.getParcelableArrayExtra("Attachments") as Array<Attachment>
attachments = a // fails with a type mismatch error
attachments = ArrayList(a) // fails again
attachments = intent.get????????("Attachments") // any such option ?
}
}
现在我的问题是,将ActivityA中的
attachments
数组添加到ActivityB中的attachments
array-list的最有效方法是什么? 最佳答案
答案很简单。
data class Attachment(val Name: String, val Content: String) : Serializable
// In ActivityB
val a: Array<SecretJSON.Attachment> = intent.getSerializableExtra("Attachments") as Array<Attachment>
attachments = a.toCollection(ArrayList())