一、声明
本文需要RecyclerView基础和View Binding的使用基础,没有的话学习完在看
二、导入依赖库
在 app模块的build.gradle的dependencies代码块中加入如下内容:
implementation com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.46
三、创建Adapter与ViewBinding的联合基类 --- BaseBindingAdapter.kt
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
abstract class BaseBindingAdapter<T, VB : ViewBinding>(data: MutableList<T>? = null) :
BaseQuickAdapter<T, BaseBindingAdapter.BaseBindViewHolder<VB>>(0, data) {
abstract fun createViewBinding(inflater: LayoutInflater, parent: ViewGroup): VB
override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseBindViewHolder<VB> {
val binding = createViewBinding(LayoutInflater.from(parent.context), parent)
return BaseBindViewHolder(binding, binding.root)
}
//支持binding的内容
class BaseBindViewHolder<VB>(var binding: VB, view: View) : BaseViewHolder(view)
}
四、具体使用
首先创建好Adapter的item布局和Bean对象,准备好BeanList数据
在代码中创建需要的adapter
//其中AppBean是你的Bean对象类型 AppinfoItemLayoutBinding 就是Item布局的ViewBinding对象
private val mAppBeanAdapter = object :
BaseBindingAdapter<AppBean, AppinfoItemLayoutBinding>() {
override fun convert(
holder: BaseBindViewHolder<AppinfoItemLayoutBinding>,
item: AppBean
) {
//这里对内容进行填充
holder.binding.appIcon.setImageDrawable(item.icon)
holder.binding.appNameTv.text = item.name
holder.binding.NumTv.text = FlowUtils.getProgressFormatted(item.dataUsage)
}
override fun createViewBinding(
inflater: LayoutInflater,
parent: ViewGroup
): AppinfoItemLayoutBinding {
return AppinfoItemLayoutBinding.inflate(inflater, parent, false)
}
}
初始化RecyclerView
binding.appBeanRecyclerView.layoutManager = LinearLayoutManager(requireContext())
mAppBeanAdapter.setNewData(AppBeanList) //传入你的BeanList,刷新数据也可以直接用这行代码,会自动刷新
binding.appBeanRecyclerView.adapter = mAppBeanAdapter