android - 移动项目时,DiffUtil 不更新回收站视图
问题描述
我在 RecyclerView 中实现了拖放,并DiffUtil
用于调度更新。但似乎项目移动并未以某种方式分派DiffUtil
给适配器。但是,如果我调用notifyItemMoved()
适配器,它就可以工作。
在适配器中
fun updateItems(items: List<Item?>) {
val diffResult = DiffUtil.calculateDiff(MyDiffCallback(this.items, items), true)
diffResult.dispatchUpdatesTo(this)
this.items = items
}
存储库
fun swap(fromPosition: Int, toPosition: Int) {
val list = liveItems.value
Collections.swap(list, fromPosition, toPosition)
liveItems.value = list
}
物品
data class Item(val id: String, @StringRes val title: Int, @DrawableRes val icon: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Item
if (id != other.id) return false
if (title != other.title) return false
if (icon != other.icon) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + title
result = 31 * result + icon
return result
}
}
MyDiffCallback
class MyDiffCallback(private val oldList: List<Item?>?, private val newList: List<Item?>) :
DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList?.size ?: 0
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList!![oldItemPosition]!!.id == newList[newItemPosition]!!.id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList!![oldItemPosition]!! == newList[newItemPosition]
}
}
请注意id
变量is specific to each
Item`。
解决方案
推荐阅读
- git - Gerrit 发布非本地更改补丁
- git - 使用 PowerShell 远程处理在 Windows Server 上安装 git
- jhipster - 添加新实体
- bbc-microbit - 从命令行生成 micropython + python 代码 `.hex` 文件
- php - 使用 php 使引导导航栏动态化
- database - MongoDB查询基于多个参数搜索用户
- java - 为什么 Collectors.toMap 需要非空值
- python - Gurobi中的分段线性函数,理解示例
- html - 关于定位 HTML
- javascript - Three.js – 将纹理应用于 Collada 网格会产生意想不到的结果