Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setHasStableIDs(true) in RecyclerView

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?

like image 246
pheww Avatar asked May 20 '17 03:05

pheww


Video Answer


2 Answers

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!.

like image 170
Harish Jose Avatar answered Sep 28 '22 07:09

Harish Jose


For new readers:

Note that for the Paging 3.0 library stable IDs are unnecessary and therefore unsupported.

Reference: https://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapter#getitemid

like image 37
Dambakk Avatar answered Sep 28 '22 06:09

Dambakk