很惭愧, 做了多年的Android开发还没有使用过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 对结果运行第二遍以检测已移动的项目。
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
}
}
}
}
DiffUtil 官方介绍
将 DiffUtil 和数据绑定与 RecyclerView 结合使用
DiffUtil和它的差量算法
DiffUtils 遇到 Kotlin,榨干视图局部刷新的最后一滴性能