android - 如何用Android RecyclerView表示列表里面的列表
问题描述
目前我有以下数据。
data class A(val b: List<B>? = null, val id: String, val title: String)
data class B(val name: String, val price: String)
服务器的数据响应是List<A>
,RecyclerView 应该显示 b 的名称和价格,当我单击 RecyclerView 时,A 的 id 值应该传递给下一个活动。
如何在 RecyclerView 中使用 RecyclerView 解决它以及如何在 RecyclerView 中添加 View 可能是解决方案,但我想知道最佳实践。
解决方案
如果您正在使用 B 的垂直 RecyclerViews 的动态数量创建 A 的垂直 RecyclerView,那么我将创建一个具有 A 和 B 扁平列表的 RecyclerView 并执行以下操作:
sealed class RecyclerItem {
data class ItemA(val id: String, val title: String): RecyclerItem()
data class ItemB(val name: String, val price: String): RecyclerItem()
}
class YourAdapter(private val recyclerItems: List<RecyclerItem>, private val onItemAClickListener: (Int) -> Unit) : ReycyclerView.Adapter<RecyclerView.ViewHolder>() {
private val TYPE_A = 0
private val TYPE_B = 1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when(viewType) {
TYPE_A -> inflater.inflate(R.layout.layout_item_a, parent, false).apply {
it.setOnClickListener {
onItemAClickListener((recyclerItems[position] as RecyclerItem.ItemA).id)
}
TYPE_B -> inflater.inflate(R.layout.layout_item_b, parent, false)
}
}
override fun getItemViewType(position: Int) = return when(recyclerItems[position]) {
is RecyclerItem.ItemA -> TYPE_A
is RecyclerItem.ItemB -> TYPE_B
}
override fun getItemCount() = recyclerItems.size
}
data class A(val b: List<B>? = null, val id: String, val title: String)
data class B(val name: String, val price: String)
val dataResponse: List<A> // response from the server with list of A
val itemsList = arrayListOf<RecyclerItem>() // list that will contain flatten A and B
dataResponse.forEach { a ->
itemsList.add(RecyclerItem.ItemA(a.id, a.title))
it.b.forEach { b ->
itemsList.add(RecyclerItem.ItemB(b.name, b.price))
}
}
// setup RecyclerView in your Activity/Fragment
val adapter = YourAdapter(itemsList) { idOfA ->
//go to next activity with id of A
}
recyclerView.adapter = adapter
如果您正在使用 B 的动态数量的水平 RecyclerViews 创建 A 的垂直 RecyclerView,那么我建议这篇博文:https ://android.jlelse.eu/easy-adding-nested-recycler-view-in-android-a7e9f7f04047
推荐阅读
- javascript - 不能匹配句子中的第二个选项
- google-apps-script - 使用从 1 开始的唯一参考编号填充 A 列的代码
- sql-server - 使用业务规则主数据服务的存储过程中的方程查询
- javascript - 尝试将数据从子级传递给父级时出现 setState 问题
- api - Slack 工作区机器人到机器人通信
- reactjs - firebase phone auth 不会重新发送代码 [React Native]
- php - WordPress admin-ajax.php 400
- angular - Angular amTimeAgo 不刷新
- c# - C# .NET Core 2.1 跨度
和记忆 性能注意事项 - r - 无法在 Rstudio 中安装 xlsx 包