如何在 kotlin 中实现 List<data class>(子列表)的 parcelable?
Posted
技术标签:
【中文标题】如何在 kotlin 中实现 List<data class>(子列表)的 parcelable?【英文标题】:How to implementation parcelable for List<data class> (child list) in kotlin? 【发布时间】:2020-12-31 19:44:51 【问题描述】:我想用 parcelable 将数据类意图用于其他活动。但是当我想打算使用变量类型列表时,我卡住了。我不知道如何实现,因为这是我第一次使用 parcelable
这是我的 POJO/模型
@Parcelize
data class HistoryTree(
val id: Int,
val landOwner: String,
val treeNumber: String,
val membershipId: String,
val speciesId: Int,
val speciesName: String,
val diameter: Double,
val areaName: String,
val woodProducts: List<HistoryProduct>) :Parcelable
@Parcelize
data class HistoryProduct(
val id: Int,
val treeId: Int,
val logStatus: Int,
val orderId: Int,
val logSequenceNumber: Int,
val logNumber: String,
val diameter: String,
val length: String,
val circumference: String,
val logType: Int,
val statusPecah: Int?,
val lubangGerek: Int?,
val pinhole: Int?,
val belimbing: Int?,
val createdBy: Int,
val deleted: Int,
val isTake: Int,
val rejectStatusPetani: Int
) : Parcelable
这是我的活动
package com.sobi.penebangan.historylist
class HistoryListActivity : AppCompatActivity(), CoroutineScope
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val vm: HistoryListViewModel by lazy ViewModelProviders.of(this, viewModelFactory).get(HistoryListViewModel::class.java)
private var trees = mutableListOf<HistoryTree>()
private val treeAdapter = object : RecyclerView.Adapter<HistoryItemViewHolder>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryItemViewHolder
val ui = HistoryItemUi()
val view = ui.createView(AnkoContext.create(parent.context, parent))
return HistoryItemViewHolder(ui, view)
override fun getItemCount(): Int = trees.size
override fun onBindViewHolder(holder: HistoryItemViewHolder, position: Int)
holder.bind(trees[position])
val product = it.woodProducts
val activity = Intent(this@HistoryListActivity, ProductHistoryListActivity::class.java)
activity.putExtra(ProductHistoryListActivity.paramTreeNumber, it.treeNumber)
activity.putExtra(ProductHistoryListActivity.paramHistoryData, it.woodProducts)
startActivity(activity)
当我想要使用变量 woodProduct 时出现错误,因为类型数据是 List
谁能帮帮我?
【问题讨论】:
***.com/a/50152749/4168607 谢谢你。我会试试的 【参考方案1】:在第一个活动中,同时将列表数据添加到意图转换为ArrayList<out Parcelable>
例如:
intent.putParcelableArrayListExtra("arrayList",it.woodProducts as
ArrayList<out Parcelable>)
然后在第二个活动中获取数据时将其转换为 ArrayList
例如:
val list = intent.extras
val prodList: List<HistoryProduct> = list?.get("arrayList") as ArrayList<HistoryProduct>
【讨论】:
以上是关于如何在 kotlin 中实现 List<data class>(子列表)的 parcelable?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Kotlin 中实现 OnClickListener 接口? [复制]