很惭愧, 做了多年的Android开发还没有使用过DiffUtil这样解放双手的工具。
1 DiffUtil 用来解决什么问题?
List发生变化, 我们使用 RecyclerView.Adapter.notifyDataChanged很熟练了
- 如果List仅仅是一个item变化了,其他item没有变化怎么办? notifyItemChanged
- 如果List仅仅是一个item移除了,其他item没有移除怎么办? notifyItemRemoved
- 如果List部分item发生变化,其他的item都没有变化怎么办?
- 如果List部分item移除了,其他item没有移除怎么办?
有如下解决思路:
- 你可以无脑继续使用notifyDataChanged 但失去了性能
- 自己判断发生变化的item,自己调用notifyItemxxx
- DiffUtil帮你判断哪里发生了变化,并自动帮你调用 notifyItemxxx
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=

本文介绍了DiffUtil在Android开发中的应用,尤其是在RecyclerView中处理列表项增删改时的高效解决方案,利用DiffUtil的差分算法计算最小更新,提升性能。作者通过示例展示了如何在实际项目中使用DiffUtil和自定义回调进行列表更新操作。
最低0.47元/天 解锁文章
784






