从包含卡片列表的数组列表传递数据



告诉我如何或如何最好地传输CardList数组(ArrayList)中包含的Card数据?
数据类卡片:

data class Card(
val id: Long,
val category: String,
val company: String,
val name: String,
val cost: Int,
val photo: String)

卡片列表:

var cardList = ArrayList<Card>()
...
cardList = (1..50).map {
val card = Card(
id = it.toLong(),
category = faker.name().name(),
company = faker.company().name(),
name = faker.name().name(),
cost = it,
photo = "https://images.unsplash.com/photo........"
)
adapter.addCard(card)
} as ArrayList<Card>

还有一个ProductActivity类,它应该基于从CardList传输的数据,在视图中替换这些值。主要任务是,在recyclerview上有卡片元素(一个50块的数组),每个元素都有自己的id,字符串值和照片图像,即数据类card值,您需要将这些值传输到ProductActivity(当您单击recyclerview中的卡片元素时,活动打开),并在此窗口中显示从CardList(数据类card值)传输的数据

让你的data-classParcelable,在build.gradle(app)中添加插件

plugins {
...
id 'kotlin-parcelize'
}

让你的数据类Parcelable

@Parcelize
data class Card (
val id: Long,
val category: String,
val company: String,
val name: String,
val cost: Int,
val photo: String
) : Parcelable
在你的onItemClick,通过intent extras传递该对象
itemView.setOnClickListener(()-> {
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("item", card)
startActivity(intent)
}

在其他活动中,

val card : Card = getIntent().getParcelableExtra("item")

最新更新