首页 > 解决方案 > 移动项目时,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 eachItem`。

标签: androidandroid-recyclerview

解决方案


推荐阅读