首页 > 解决方案 > 如何用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 可能是解决方案,但我想知道最佳实践。

标签: androidandroid-recyclerview

解决方案


如果您正在使用 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


推荐阅读