hasStableIds的作用

如果hasStableIds返回false的話 每次調用notifyDataSetChanged方法時 adapter就會判斷getItemId 並且在只調用那些Item發生變化的getView方法,說白了就是通過getItemId來判斷那些需要getView從而達到局部刷新的效果,在getView比較耗時的情況下起到優化的效果。下面是stackoverflow的原文,並給出了用例。


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) only for thous items which id has changed.

Using this technique you can easelly 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 then and call notifyDataSetChanged() on your adapter, then the adapter will call getItemId() method of each element and update only thouse items which id has changed.

This is very useful if are doing some "heavy" operations in your getView().



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章