RecyclerView-DiffUtil

1.前言

2.工具类要点

2.1 声明并初始化AsyncListDiffer

private val mDiffer: AsyncListDiffer<T> 

2.2 创建DiffUtil.ItemCallback<T>,实现抽象方法

abstract fun areItemsTheSame(oldItem: T, newItem: T): Boolean
abstract fun areContentsTheSame(oldItem: T, newItem: T): Boolean

2.3 更新数据

fun setData(list: MutableList<T>?) {
    val newList: MutableList<T> = ArrayList()
    newList.addAll(list ?: ArrayList())
    mDiffer.submitList(newList) // 更新数据(setData()+notify())
}

3. 注意事项

3.1 不能重复提交同一个列表

  • 更新数据前(调用submitList(List<T> newList)),请勿对"已被设置进DiffUtil的list数据"进行操作。
  • 需重新创建list,以便DiffUtil进行两个新旧列表间对比。如举例。

3.2 错误示范

mData.add(...)
mAdapter.submitList(mData)

3.3 引发此问题原因

public class AsyncListDiffer<T> {
    // 更新数据
    public void submitList(@Nullable final List<T> newList, @Nullable final Runnable commitCallback) {
        // incrementing generation means any currently-running diffs are discarded when they finish
        final int runGeneration = ++mMaxScheduledGeneration;
        if (newList == mList) { // 此处进行了过滤
            // nothing to do (Note - still had to inc generation, since may have ongoing work)
            if (commitCallback != null) {
                commitCallback.run();
            }
            return;
        }
        ...
    }
}

4. 基类封装实现

使用DiffUtil进行RecyclerView数据的对比&刷新,把相关api进行二次封装,以便为了更简单调用。

4.1 BaseRecyclerDifferItemCallBack

  • DiffUtil.ItemCallback<T>进行二次封装。
  • RecyclerView的dapter作为参数,把对比函数回调到Adapter进行实现。
class BaseRecyclerDifferItemCallBack<T>(adapter: BaseRecyclerDifferAdapter<T>?) :
        DiffUtil.ItemCallback<T>() {

    private var mAdapter: BaseRecyclerDifferAdapter<T>? = adapter

    override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
        return mAdapter?.areItemsTheSame(oldItem, newItem)?: false
    }

    override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
        return mAdapter?.areContentsTheSame(oldItem, newItem)?: false
    }
}

4.2 BaseRecyclerDifferAdapter

  • RecyclerView.Adapter进行二次封装,初始化AsyncListDiffer变量用于数据操作。
  • 创建数据对比抽象方法,用于此Adapter子类实现
abstract class BaseRecyclerDifferAdapter<T> : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val mDiffer: AsyncListDiffer<T> by lazy {
        // 数据的操作由AsyncListDiffer实现
        AsyncListDiffer(this, BaseRecyclerDifferItemCallBack<T>(this))
    }

    fun getCurrentData(): MutableList<T> {
        return mDiffer.currentList
    }

    /**
     * 设置数据
     * @param list MutableList<T>?
     */
    fun setData(list: MutableList<T>?){
        val newList: MutableList<T> = ArrayList()
        newList.addAll(list?: ArrayList())
        mDiffer.submitList(newList)
    }


    /**
     * 添加数据
     * @param beans Array<out T>
     */
    fun addData(vararg beans: T) {
        val newList: MutableList<T> = ArrayList()
        newList.addAll(mDiffer.currentList)
        beans.forEach { bean ->
            newList.add(bean)
        }
        mDiffer.submitList(newList)
    }

    /**
     * 加载更多
     * @param list MutableList<T>?
     */
    fun loadMore(list: MutableList<T>?){
        val newList: MutableList<T> = ArrayList()
        newList.addAll(mDiffer.currentList)
        newList.addAll(list?: ArrayList())
        mDiffer.submitList(newList)
    }

    /**
     * 删除数据
     * @param index Int
     */
    fun removeData(index: Int) {
        val newList: MutableList<T> = ArrayList()
        val currentList = mDiffer.currentList
        if (currentList.isNotEmpty() && index in 0 until currentList.size) {
            newList.addAll(currentList)
            newList.removeAt(index)
            mDiffer.submitList(newList)
        }
    }

    /**
     * 清空数据
     */
    fun clear() {
        mDiffer.submitList(null)
    }

    abstract fun areItemsTheSame(oldItem: T, newItem: T): Boolean
    abstract fun areContentsTheSame(oldItem: T, newItem: T): Boolean

4.2 业务Adapter实现

  • 举例说明BaseRecyclerDifferAdapter使用方式
  • 以下为伪代码,仅包含关键实现
class RVDifferAdapter(context: Context) : BaseRecyclerDifferAdapter<RVDifferBean>() {
    
    private var mContext: Context = context

    /**
     * Item对比
     */
    override fun areItemsTheSame(oldItem: RVDifferBean, newItem: RVDifferBean): Boolean {
        return oldItem.id == newItem.id // 比较逻辑自行实现
    }
    
    /**
     * Content对比
     */
    override fun areContentsTheSame(oldItem: RVDifferBean, newItem: RVDifferBean): Boolean {
        return oldItem.name == newItem.name // 比较逻辑自行实现
    }

    private var mInflater: LayoutInflater = LayoutInflater.from(context)

    /**
     * 获取单条item数据
     *
     * @param position
     * @return
     */
    private fun getItemAtPosition(position: Int): RVDifferBean? {
        val itemCount: Int = itemCount
        return if (itemCount != 0 && position in 0 until itemCount) {
            getCurrentData()[position]
        } else {
            null
        }
    }

    override fun getItemCount(): Int {
        return getCurrentData().size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {}

    override fun onBindViewHolder(
        holder: RecyclerView.ViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        super.onBindViewHolder(holder, position, payloads)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    }
}

参考文档:

官方文档地址:[https://developer.android.google.cn/reference/kotlin/androidx/recyclerview/widget/DiffUtil]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容