setHasStableIDs(true) in RecyclerView

pheww picture pheww · May 20, 2017 · Viewed 12.1k times · Source

I am new to android and got stuck when I click on an item in RecyclerView where the data set gets changed and position doesn't match with the ID in SQLite.I know we can get unique ID by using 'setHasStableID' but I was little confused as to where do I need to set this 'setHasStableId(true)' condition? How does this work?

Answer

Harish Jose picture Harish Jose · Aug 7, 2018

The setHasStableIds(true) is to be applied to the adapter of RecylerView.

adapter.setHasStableIds(true);

Also for this to be taken effect you must have to 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 id can be an id from the database which will be unique for each item and are not changed throughout.

//Inside the Adapter class
@Override
public long getItemId(int position) {
    return itemList.get(position).getId();
}

This will reduce the blinking effect on dataset notify, where it modifies only items with changes.

And the great part is it will add cool animations on item position changes!.