Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent RecyclerView item from blinking after notifyItemChanged(pos)?

I currently have a recycler view whose data updates every 5 secs. To update the data on the list, I am using

notifyItemChanged(position);
notifyItemRangeChanged(position, mList.size());

Each time I call notifyItemChanged(), the items on my recycler view update properly, however, it will blink because this causes onBindViewHolder to be called again. So it's as though it is a fresh load each time. How can I prevent this from happening, if possible?

like image 992
portfoliobuilder Avatar asked Feb 21 '17 23:02

portfoliobuilder


3 Answers

You can disable the item animations.

mRecyclerView.setItemAnimator(null);
like image 39
Buddy Avatar answered Nov 07 '22 01:11

Buddy


RecyclerView has built in animations which usually add a nice polished effect. in your case you'll want to disable them:

((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);

(The default recycler view animator should already be an instance of SimpleItemAnimator)

For Kotlin,

(mRecyclerView?.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
like image 149
Nick Cardoso Avatar answered Nov 07 '22 01:11

Nick Cardoso


The problem may not come from animation but from not stable id of the list item.

To use stable IDs, you need to:

- setHasStableIds(true)
In RecyclerView.Adapter, we need to set setHasStableIds(true); true means this adapter would publish a unique value as a key for item in data set. Adapter can use the key to indicate they are the same one or not after notifying data changed.

- override getItemId(int position)
Then we must override getItemId(int position), to return identified long for the item at position. We need to make sure there is no different item data with the same returned id.

The source of solution for that is here.

like image 19
Marian Paździoch Avatar answered Nov 07 '22 02:11

Marian Paździoch