I'm implementing a ListAdapter of ExpandableListView, while working i see that i need to overide the function boolean hasStableIds(). Can anyone explain please what is the meaning of stable ids? when I need this?
Stable IDs allow the ListView
to optimize for the case when items remain the same between notifyDataSetChanged
calls. The IDs it refers to are the ones returned from getItemId
.
Without it, the ListView
has to recreate all View
s since it can't know if the item IDs are the same between data changes (e.g. if the ID is just the index in the data, it has to recreate everything). With it, it can refrain from recreating View
s that kept their item IDs.
true
when an id
is guaranteed to refer to a particular unique object, such that a change in id
signifies an object changed and an id
remaining the same means it is not some new object returning the same id
in which case the view would have to be updated and the method would be required to return false
. –
Hortensiahorter RecycledViewPool
and should be recycled. To me the advantage of stable Ids is that you don't need to bind them again. Or do I miss something ? –
Illjudged If hasStableIds()
returns false
then each time you call notifyDataSetChanged()
your Adapter will look at the returned value of getItemId
and will eventually call getView(int position, View convertView, ViewGroup parent)
. If hasStableIds()
returns true
the this will only be done when their id has changed.
Using this technique you can easily update only one Item in the ListView
If you implement getItemId
correctly then it might be very useful.
Example :
You have a list of albums :
class Album{
String coverUrl;
String title;
}
And you implement getItemId
like this :
@Override
public long getItemId(int position){
Album album = mListOfAlbums.get(position);
return (album.coverUrl + album.title).hashCode();
}
Now your item id depends on the values of coverUrl and title fields and if you change them and call notifyDataSetChanged()
on your adapter, then the adapter will call getItemId() method of each element and update only those items which id has changed.
This is very useful if are doing some "heavy" operations in your getView()
.
hashCode()
returns the same number for 2 different strings (i.e. you have a hash codes collision)? And generalizing, if your getItemId(int position)
returns not unique IDs. how it affects the ListView
? –
Epiblast © 2022 - 2024 — McMap. All rights reserved.