DiffUtils不显示新项目

时间:2018-07-05 10:55:24

标签: android android-recyclerview recycler-adapter

DiffUtils.dispatchUpdatesTo(adapter)未更新recyclerView中的数组大小

我的result的大小比当前itemList大,但仅显示当前大小

如何显示DiffUtils数组大小的变化?我认为使用notifyDatasetChanged()是不正确的。

这是我现在在适配器中执行的操作:

    fun update(items: List<ITEM>) {
    updateAdapterWithDiffResult(calculateDiff(items))
}

private fun updateAdapterWithDiffResult(result: DiffUtil.DiffResult) {
    result.dispatchUpdatesTo(this)
}

private fun calculateDiff(newItems: List<ITEM>) =
        DiffUtil.calculateDiff(DiffUtilCallback(itemList, newItems))

1 个答案:

答案 0 :(得分:6)

您的列表大小没有更新,因为您没有在 itemList

中添加新项目

像这样更新您的代码-

class YourAdapter(
    private val itemList: MutableList<ITEM>
) : RecyclerView.Adapter<YourAdapter.ViewHolder>() {

.
.
.

    fun updateList(newList: MutableList<ITEM>) {
        val diffResult = DiffUtil.calculateDiff(
                DiffUtilCallback(this.itemList, newList))

        itemList.clear()
        itemList.addAll(newList)

        diffResult.dispatchUpdatesTo(this)
    }
}

希望它对您有用。

相关问题