Open luke-li-n opened 4 months ago
+1
同问
临时解决方案: 使用现有的BaseDifferAdapter 自己实现多类型逻辑
MultiItemProvider
abstract class MultiItemProvider<T, VH : RecyclerView.ViewHolder> {
abstract fun onBind(holder: VH, position: Int, item: T?)
abstract fun onCreate(context: Context, parent: ViewGroup, viewType: Int): VH
}
Adapter
class DifferAdapter() :BaseDifferAdapter<UiData, RecyclerView.ViewHolder>(DiffCallBack()) {
private val textMessageItemProvider =
object : MultiItemProvider<UiData, TextViewHolder>() {
override fun onBind(holder: TextViewHolder, position: Int, item: UiData?) {
}
override fun onCreate(
context: Context, parent: ViewGroup, viewType: Int
): TextViewHolder{
return TextViewHolder(parent)
}
}
private val messageItemProviders = mapOf(
SupportType.Text.type to textItemProvider,
SupportType.Unknown.type to unknownItemProvider
)
override fun getItemViewType(position: Int, list: List<UiData>): Int {
val item = getItem(position)
return item?.messageType?.type ?: SupportType.Unknown.type
}
override fun onCreateViewHolder(
context: Context,
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
val provider: MultiItemProvider<UiMessage, out RecyclerView.ViewHolder> =
messageItemProviders[viewType]
?: throw IllegalArgumentException("No provider found for message type: ${viewType}")
return provider.onCreate(parent.context, parent, viewType)
}
override fun onBindViewHolder(
holder: RecyclerView.ViewHolder,
position: Int,
item: UiData?
) {
val provider: MultiItemProvider<UiMessage, out RecyclerView.ViewHolder> =
messageItemProviders[item?.messageType?.type]
?: throw IllegalArgumentException("No provider found for message type: ${item?.messageType?.type}")
@Suppress("UNCHECKED_CAST")
(provider as MultiItemProvider<UiMessage, RecyclerView.ViewHolder>).onBind(
holder,
position,
item
)
}
}
v4版本BaseMultiItemAdapter如何支持Differ?