DiffUtils不显示新项目

Top*_*per 9 android recycler-adapter android-recyclerview

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))
Run Code Online (Sandbox Code Playgroud)

D_A*_*pha 12

您的列表大小没有更新,因为您没有在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)
    }
}
Run Code Online (Sandbox Code Playgroud)

希望它对您有用。

  • 是的,它可以工作,但是diffutils为什么不自己做呢? (10认同)
  • @SirojiddinKomolov 不会 `itemList.clear()` `itemList.addAll(newList)` 做与 `notifyDataSetChanged()` 相同的事情吗?那么有什么必要使用DiffUtil呢? (8认同)
  • 因为可能您根据列表 itemList 实现了函数 getItemCount() ,而 diffUtils 无法自行更改函数的内容,您应该自己执行此操作。也许将来 Google 开发人员会考虑 diffutils 来改变 Adapter 的结构 (2认同)