How to update RecyclerView Adapter Data?

前端 未结 13 2557
误落风尘
误落风尘 2020-11-22 03:48

Trying to figure out what is the issue with updating RecyclerView\'s Adapter.

After I get a new List of products, I tried to:

  1. Update t

13条回答
  •  暖寄归人
    2020-11-22 04:12

    Another option is to use diffutil . It will compare the original list against the new list and use the new list as the update if there is a change.

    Basically, we can use DiffUtil to compare the old data vs new data and let it call notifyItemRangeRemoved, and notifyItemRangeChanged and notifyItemRangeInserted on your behalf.

    A quick example of using diffUtil instead of notifyDataSetChanged:

    DiffResult diffResult = DiffUtil
                    .calculateDiff(new MyDiffUtilCB(getItems(), items));
    
    //any clear up on memory here and then
    diffResult.dispatchUpdatesTo(this);
    
    //and then, if necessary
    items.clear()
    items.addAll(newItems)
    

    I do the calculateDiff work off the main thread in case it's a big list.

提交回复
热议问题