Android - what is the meaning of StableIDs?

后端 未结 2 740
[愿得一人]
[愿得一人] 2020-11-29 06:06

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

2条回答
  •  清酒与你
    2020-11-29 06:41

    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 getItemIdcorrectly 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().

提交回复
热议问题