John
John

Reputation: 31

Android RecyclerView adapter items refresh

I am having a problem with the RecyclerView and the RecyclerView.Adapter. I got a function that sets a list of items into the adapter. When user swipe-to-refresh, I load fresh data which means some items are new, then I set the items into adapter and I have to invalidate them. My problem is with notifyItemRangeInserted() and notifyItemRangeChanged(). When new items appear, if I first remove them, then notifyItemRangeRemoved(), then add and finally call notifyItemRangeInserted() it would work, but all items are invalidated and it blinks. Otherwise, if I determine the diff in size between new and old data set, it is not invalidating the proper elements.

public void setItems(@NonNull List<ItemType> items) {
        final int oldSize = mItems.size();
        mItems.clear();
        notifyItemRangeRemoved(firstPosition(), oldSize);
        mItems.addAll(items);
        notifyItemRangeInserted(firstPosition(), items.size());
}

mItems is ArrayList.

Upvotes: 3

Views: 1205

Answers (3)

John
John

Reputation: 31

The resolution was to use hasStableIds() in the adapter so the adapter can find out which items are changed.

Upvotes: 0

Simon
Simon

Reputation: 19948

I think maybe you are overthinking the situation.

Similar to Hiren's answer, you can just:

public void setItems(@NonNull List<ItemType> items) {
   mItems.clear(); 
   mItems.addAll(items);
   myRecycleAdapter.notifyDataSetChanged(); }

NotifyDataSetChanged will neither cause the blinking effect nor more your list from its current position.

Upvotes: 0

Hiren Patel
Hiren Patel

Reputation: 52810

Can you please try this one ?

myRecycleAdapter.notifyItemInserted(items.size());

Your method would looks like below:

public void setItems(@NonNull List<ItemType> items) {
   mItems.clear();
   mItems.addAll(items);
   myRecycleAdapter.notifyItemInserted(items.size());

}

Hope this will help you.

Upvotes: 1

Related Questions