DiffUtil + RecyclerView 在 Kotlin中的使用

很惭愧, 做了多年的Android开发还没有使用过DiffUtil这样解放双手的工具。

1 DiffUtil 用来解决什么问题?

先举几个实际开发中的例子帮助我们感受下:

  • 加载内容流时,第一次加载了ABC,第二次加载了BCD,如何让用户能看到不重复的内容?
  • 网络数据和本地数据不一致, 如何能够找出不一致的内容?

我们可以采用最笨的方法, 自己比较两个集合的差异,但是效率较低,每个开发者都要重复做这样的事情, 是谷歌不愿意看到的。

2 DiffUtil 是什么?

DiffUtil is a utility class that calculates the difference between two lists and outputs a list of update operations that converts the first list into the second one.

It can be used to calculate updates for a RecyclerView Adapter. See ListAdapter and AsyncListDiffer which can simplify the use of DiffUtil on a background thread.

DiffUtil uses Eugene W. Myers’s difference algorithm to calculate the minimal number of updates to convert one list into another. Myers’s algorithm does not handle items that are moved so DiffUtil runs a second pass on the result to detect items that were moved.

DiffUtil 是一个实用程序类,它计算两个列表之间的差异并输出将第一个列表转换为第二个列表的更新操作列表。

它可用于计算 RecyclerView 适配器的更新。请参阅 ListAdapter 和 AsyncListDiffer,它们可以简化后台线程上 DiffUtil 的使用。

DiffUtil 使用 Eugene W. Myers 的差分算法来计算将一个列表转换为另一列表所需的最小更新次数。 Myers 的算法不处理已移动的项目,因此 DiffUtil 对结果运行第二遍以检测已移动的项目。

3 DiffUtil的使用

item_song_info.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <!-- Title TextView -->
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textSize="20sp"
        android:textStyle="bold" />

    <!-- Spacer View to add space between title and subtitle -->
    <View
        android:layout_width="8dp"
        android:layout_height="match_parent" />

    <!-- Subtitle TextView -->
    <TextView
        android:id="@+id/tv_sub_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subtitle"
        android:textSize="16sp" />
</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MusicBean.kt

data class MusicBean(var type: Int, var title: String, val subTitle: String)

MainActivity.kt

class MainActivity : AppCompatActivity() {
   

    override fun onCreate(savedInstanceState: Bundle?) {
   
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        val adapter = MyAdapter()
        recyclerView.adapter = adapter

        adapter.data = getSampleDataA()

        Handler(Looper.getMainLooper()).postDelayed({
   
            adapter.data = getSampleDataB()
        }, 2000)
    }


    // 用于生成初始数据
    private fun getSampleDataA(): List<MusicBean> {
   
        val data = mutableListOf<MusicBean>()
        for (i in 1..10) {
   
            MusicBean(type = i, title = "ItemA $i", subTitle = "subTitle $i").let {
   
                data.add(it)
            }
        }
        return data
    }

    // 用于生成变化后的数据
    private fun getSampleDataB(): List<MusicBean> {
   
        val data = mutableListOf<MusicBean>()
        for (i in 1..10) {
   
            val tag = if (i <= 5) {
   
                "B"
            } else "A"
            MusicBean(type = i, title = "Item$tag $i", subTitle = "subTitle $i").let {
   
                data.add(it)
            }
        }
        return data
    }


    class MyAdapter : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
   

        var data: List<MusicBean> = emptyList()
            set(value) {
   
                // 如果比较的集合较多(比如超过1000个), 建议使用子线程去比较
                val diffResult = DiffUtil.calculateDiff(MyDiffCallback(field, value))
                // 旧值赋新值
                field = value
                // 这里一定要保证在主线程调用
                diffResult.dispatchUpdatesTo(this)
            }

        class MyDiffCallback(
            private val oldList: List<MusicBean>, private val newList: List<MusicBean>
        ) : DiffUtil.Callback() {
   

            override fun getOldListSize(): Int = oldList.size
            override fun getNewListSize(): Int = newList.size

            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
   
                // 把这里想成是比较holder的类型, 比如纯文本的holder和纯图片的holder的type肯定不同
                return oldList[oldItemPosition].type == newList[newItemPosition].type
            }

            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
   
                // 把这里想成是同一种holder的比较,比如都是纯文本holder,但是title不一致
                return oldList[oldItemPosition].title == newList[newItemPosition].title
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
   
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_song_info, parent, false)
            return MyViewHolder(view)
        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
   
            val item = data[position]
            holder.bind(item)
        }

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

        class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
   

            fun bind(item: MusicBean) {
   
                val tvTitle: TextView = itemView.findViewById(R.id.tv_title)
                val tvSubTitle: TextView = itemView.findViewById(R.id.tv_sub_title)
                tvTitle.text = item.title
                tvSubTitle.text = item.subTitle
            }
        }
    }
}

在这里插入图片描述

4 参考文章

DiffUtil 官方介绍
将 DiffUtil 和数据绑定与 RecyclerView 结合使用
DiffUtil和它的差量算法
DiffUtils 遇到 Kotlin,榨干视图局部刷新的最后一滴性能

相关推荐

  1. kotlinsealed语句使用

    2023-12-19 14:48:01       34 阅读
  2. Kotlinobject关键字使用

    2023-12-19 14:48:01       39 阅读
  3. kotlin使用myibatis-pluslambdaQuery问题

    2023-12-19 14:48:01       14 阅读
  4. Kotlin委托

    2023-12-19 14:48:01       37 阅读
  5. kotlin 字符

    2023-12-19 14:48:01       9 阅读
  6. kotlin 布尔

    2023-12-19 14:48:01       8 阅读
  7. Kotlin对生成二维码使用详解

    2023-12-19 14:48:01       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-19 14:48:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-19 14:48:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-19 14:48:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-19 14:48:01       18 阅读

热门阅读

  1. 张嘉译的作业

    2023-12-19 14:48:01       58 阅读
  2. MATLAB信息统计与分析

    2023-12-19 14:48:01       40 阅读
  3. 状态管理@State

    2023-12-19 14:48:01       37 阅读
  4. 集成测试:确保软件系统无缝协同的关键

    2023-12-19 14:48:01       36 阅读
  5. [Unity--热更新之增量更新介绍]

    2023-12-19 14:48:01       42 阅读
  6. 帕金森病患者的运动锻炼有哪些建议?

    2023-12-19 14:48:01       34 阅读
  7. nginx学习--2023-12-18

    2023-12-19 14:48:01       32 阅读