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