setHasStableIDs(true) in RecyclerView
Asked Answered
S

3

10

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?

Seal answered 20/5, 2017 at 3:20 Comment(0)
E
21

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

Endora answered 7/8, 2018 at 6:54 Comment(0)
S
9

To solve blinking issue, we need to reuse the same ViewHolder and view for the same item. because

  1. RecycleView disabled stable IDs by default.
  2. So generally after notifyDataSetChanged(), RecyclerView.Adapter didn’t assigned the same ViewHolder to original item in the data set.

So solution is :-

setHasStableIds(true) :-

  • set setHasStableIds(true); in RecyclerView.Adapter .
  • 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.

Somewhere answered 17/1, 2020 at 7:9 Comment(0)
B
2

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

Blackman answered 21/8, 2020 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.