您的位置:首页 > 其它

hasStableIds的作用

2015-11-10 20:41 495 查看
如果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
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 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()
.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: