美文网首页经验之谈安卓应用层
ListView中notifyDataSetChanged()无

ListView中notifyDataSetChanged()无

作者: 梦工厂 | 来源:发表于2015-08-30 22:03 被阅读1742次

在使用ListView需要动态刷新数据的时候,经常会用到notifyDataSetChanged()函数。
以下为两个使用的错误实例:

  1. 无法刷新:
    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.

相关文章

网友评论

本文标题:ListView中notifyDataSetChanged()无

本文链接:https://www.haomeiwen.com/subject/phakcttx.html