Android DiffUtils不显示新项目
Android DiffUtils不显示新项目,android,android-recyclerview,Android,Android Recyclerview,DiffUtils.dispatchUpdatesTo(适配器)在recyclerView中不更新我的数组大小 我的结果的大小大于当前的项目列表,但只显示当前大小 如何通过DiffUtils显示阵列大小的更改?我认为使用notifyDatasetChanged()是不正确的 下面是我现在在adapter中执行此操作的方法: fun update(items: List<ITEM>) { updateAdapterWithDiffResult(calculateDiff
DiffUtils.dispatchUpdatesTo(适配器)
在recyclerView中不更新我的数组大小
我的结果
的大小大于当前的项目列表
,但只显示当前大小
如何通过DiffUtils
显示阵列大小的更改?我认为使用notifyDatasetChanged()
是不正确的
下面是我现在在adapter中执行此操作的方法:
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))
fun更新(项目:列表){
UpdateDapterWithDiffresult(计算偏差(项目))
}
private fun UpdateDapterWithDiffresult(结果:DiffUtil.DiffResult){
结果。dispatchUpdatesTo(此)
}
private fun calculateDiff(新项目:列表)=
DiffUtil.calculateDiff(DiffUtilCallback(itemList,newItems))
您的列表大小没有更新,因为您没有在项目列表中添加新项目
像这样更新您的代码-
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)
}
}
class适配器(
private val itemList:MutableList
):RecyclerView.Adapter(){
.
.
.
乐趣更新列表(newList:MutableList){
val衍射结果=DiffUtil.calculateDiff(
DiffUtilCallback(this.itemList,newList))
itemList.clear()
itemList.addAll(newList)
dispatchUpdatesTo(此)
}
}
希望它能为您工作。是的,它能工作,但是为什么diffutils不能自己做呢?因为您可能根据列表itemList实现了函数getItemCount(),而diffutils不能自己更改函数的内容,您应该自己做。也许在将来,Google开发人员会考虑到DiffUtil而改变适配器的结构。DiffUtil不改变您的实现或列表内容肯定是更好的做法,这将违反不变性规则。@SirojiddinKomolov不itemList.clear()
itemList.addAll(newList)
执行与notifyDataSetChanged()相同的操作。
?那么有什么必要使用DiffUtil呢?