您的位置:首页 > 其它

How to clear the views which are held in the ListView's RecycleBin?

2013-07-26 16:33 537 查看
android 的listview 控件,我自己使用了converview来进行缓存设置(不懂什么是convertview的请自行百度),但是发现在某些情况下会有问题。具体而言,我的问题是这样的:我需要点击一下listview的某一项,此时需要更新数据,让listview显示新的数据。而此时,由于缓存的设置,会导致更新并没有办法显示,这个时候调用notifyDataSetChanged是没有效果的。所以我们需要将缓存清除。

而我找了很久,都没有发现可以清除缓存的方法。有人说用invalidate方法,但是经过测试也没有用。

这个时候看到有人说重新设置一下adapter就可以清除缓存了,发现还是不行

Calling invalidate() or invalidateViews() did
not do the trick for me (as mentioned in the correct answer). The recycled views were still stored in the ListView.
I had to dig in Android source code to find a solution. I checked many methods, including the setAdapter() method
of the ListView class
(Android
API 15
) :

@Override
public void setAdapter(ListAdapter adapter) {

// ...
mRecycler.clear();
// ...

}

As you noticed, setting an adapter clears the recycler, which holds all the recycled views in a list view. You do not have to create a new adapter, setting the same adapter is enough to clear the recycled views list in the list view :

Adapter adapter = listview.getAdapter ();
// ... Modify adapter ... do anything else you need to do
// To clear the recycled views list :
listview.setAdapter ( adapter );

在我的项目中,adapter是作为全局变量的,所以我是这样使用的:
adDeviceList.setList(MainService.mainService.nowResult);

lvDevices.setAdapter(adDeviceList);

最后发现还是没有效果

最后我把2种方法放在一起,居然解决了...看来这2个都要设置才可以清除缓存

lvDevices.invalidateViews();

adDeviceList.setList(MainService.mainService.nowResult);

lvDevices.setAdapter(adDeviceList);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐