CymChad / BaseRecyclerViewAdapterHelper

BRVAH:Powerful and flexible RecyclerAdapter
http://www.recyclerview.org/
MIT License
24.36k stars 5.16k forks source link

v4版本BaseMultiItemAdapter增加diff支持(临时解决) #3873

Open luke-li-n opened 4 months ago

luke-li-n commented 4 months ago

v4版本BaseMultiItemAdapter如何支持Differ?

Suguiqiang commented 3 months ago

+1

xiangsss commented 3 months ago

同问

luke-li-n commented 1 month ago

临时解决方案: 使用现有的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
        )
    }
}