ListAdapter 不更新 RecyclerView 中的项目:数据改变但 UI 不重绘
大家好!我是 Kotlin 和 Android 开发的新手。我在 RecyclerView 中使用 ListAdapter,但遇到了一个奇怪的问题:当我更改列表中的数据并调用 submitList() 时,屏幕上的项目没有更新。这是我的代码:
```kotlin
data class Item(val id: Int, var title: String, var isCompleted: Boolean)
class ItemDiffCallback : DiffUtil.ItemCallback- () {
override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem == newItem
}
}
class ItemAdapter : ListAdapter
- (ItemDiffCallback()) {
// ... ViewHolder 和 bind
}
// 在 Activity 中
val items = mutableListOf(
Item(1, "任务 1", false),
Item(2, "任务 2", true)
)
adapter.submitList(items)
// 尝试更新项目
items[0].isCompleted = true
adapter.submitList(items) // 不生效!
```
我