物品移动时DiffUtil不会更新recyclerview

时间:2019-04-14 13:06:48

标签: android android-recyclerview

我在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项目`。

0 个答案:

没有答案