如果适配器接收单一数据类型对象,我知道如何实现 DiffUtil。
但就我而言,我有一个适配器,它从一个片段中获取两种数据类型。
那么如何将 DiffUtil 与多种数据类型一起使用呢?
这是我的适配器代码:
class VisitorsAdapter(val listener: VisitorsViewHolder.OnVisitorClicked) :
RecyclerView.Adapter<BaseViewHolder<*>>() {
private var visitorsData = mutableListOf<Any>()
private var isOwner = true
fun setData(visitorsData: List<Any>) {
Log.e("TAG", "setData called")
this.visitorsData.clear()
var currentVisitors = mutableListOf<CurrentVisitorResponseItem>()
var leavedVisitors = mutableListOf<LeavedVisitorsResponseItem>()
for (visitor in visitorsData) {
when (visitor) {
is CurrentVisitorResponseItem -> currentVisitors.add(visitor)
is LeavedVisitorsResponseItem -> leavedVisitors.add(visitor)
}
}
currentVisitors = currentVisitors.sortedBy { it.roomNumber?.toInt() }.toMutableList()
leavedVisitors = leavedVisitors.sortedBy { it.room }.toMutableList()
this.visitorsData.addAll(currentVisitors)
this.visitorsData.addAll(leavedVisitors)
notifyDataSetChanged()
}
fun isOwner(chooser: Boolean) {
this.isOwner = chooser
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<*> {
return VisitorsViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.visitor_item, parent, false)
)
}
override fun getItemCount() = visitorsData.size
override fun onBindViewHolder(holder: BaseViewHolder<*>, position: Int) {
val dataPositioned = visitorsData[position]
when (holder) {
is VisitorsViewHolder -> {
holder.bind(dataPositioned, position, listener, isOwner)
}
}
}
}
注意:我有两种类型的数据:
1- CurrentVisitorResponseItem
2- LeavedVisitorResponseItem