在使用ListView需要動態(tài)刷新數(shù)據(jù)的時候,經(jīng)常會用到notifyDataSetChanged()函數(shù)。
以下為兩個使用的錯誤實例:
- 無法刷新:
private List<RecentItem> recentItems;
......
recentItems = getData()
mAdapter.notifyDataSetChanged();
正常刷新:
private List<RecentItem> recentItems;
......
recentItems.clear();
recentItems.addAll(getData);
mAdapter.notifyDataSetChanged();
原因:
mAdapter通過構(gòu)造函數(shù)獲取List a的內(nèi)容,內(nèi)部保存為List b;此時,a與b包含相同的引用,他們指向相同的對象。
但是在語句recentItems = getData()之后,List a會指向一個新的對象。而mAdapter保存的List b仍然指向原來的對象,該對象的數(shù)據(jù)也并沒有發(fā)生改變,所以Listview并不會更新。
我在頁面A中綁定了數(shù)據(jù)庫的數(shù)據(jù),在頁面B中修改了數(shù)據(jù)庫中的數(shù)據(jù),希望在返回頁面A時,ListView刷新顯示。
無法刷新:
protected void onResume() {
mAdapter.notifyDataSetChanged();
super.onResume();
}
正常刷新:
protected void onResume() {
recentItems.clear();
recentItems.addAll(recentDB.getRecentList());
mAdapter.notifyDataSetChanged();
super.onResume();
}
原因:
mAdapter內(nèi)部的List指向的是內(nèi)存中的對象,而不是數(shù)據(jù)庫。所以改變數(shù)據(jù)庫中的數(shù)據(jù),并不會影響該對象。
notifyDataSetChanged()
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.