Apply toCymChad/BaseRecyclerViewAdapterHelper
// Build. Gradle adds ViewBinding support to Android {... buildFeatures { viewBinding true } }Copy the code
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.chad.library.adapter.base.viewholder.BaseViewHolder
class VBBaseViewHolder<VB : ViewBinding>(val binding: VB) : BaseViewHolder(binding.root)
/** * Adapter base class */
abstract class VBBaseQuickAdapter<T, VB : ViewBinding>(
private val inflate: (LayoutInflater, ViewGroup, Boolean) -> VB,
layoutResId: Int = 0
) :BaseQuickAdapter<T, VBBaseViewHolder<VB>>(layoutResId) {
override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): VBBaseViewHolder<VB> {
val viewBinding = inflate(LayoutInflater.from(parent.context), parent,false)
return VBBaseViewHolder(viewBinding)
}
}
/** * Multiple layout Adapter base class */
abstract class VBBaseMultiItemQuickAdapter <T : MultiItemEntity> :BaseMultiItemQuickAdapter<T, VBBaseViewHolder<ViewBinding>>() {
private val bindings: SparseArray<(LayoutInflater, ViewGroup, Boolean) -> ViewBinding> by lazy(LazyThreadSafetyMode.NONE) {
SparseArray<(LayoutInflater, ViewGroup, Boolean) -> ViewBinding>()
}
fun addViewBinding(type: Int,inflate: (LayoutInflater.ViewGroup.Boolean) - >ViewBinding){
bindings.put(type, inflate)
}
override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): VBBaseViewHolder<ViewBinding> {
val inflate = bindings.get(viewType) require(inflate ! =null) { "ViewType: $viewTypeFound ViewBinding, please use addViewBinding() first!" }
val viewBinding = inflate(LayoutInflater.from(parent.context), parent,false)
return VBBaseViewHolder(viewBinding)
}
}
Copy the code
use
Ordinary Adapter
class MyAdapter:VBBaseQuickAdapter<String,ABinding>(ABinding::inflate){
override fun convert(holder: VBBaseViewHolder<ABinding>, item: String){ holder.binding... }}Copy the code
Many layout Adapter
class MyAdapter:VBBaseMultiItemQuickAdapter<MultiItemEntity>() {init {
addViewBinding(0, ABinding::inflate)
addViewBinding(1, BBinding::inflate)
}
override fun convert(holder: VBBaseViewHolder<ViewBinding>, item: MultiItemEntity) {
holder.binding.apply {
if (this is ABinding) {
...
}else if (this isBBinding){ ... }}}}Copy the code