Android ListView控件使用 notifyDataSetChanged 未能正确刷新原因

adapter.notifyDataSetChanged();//此方法是可以实现刷新list,但很可能会有一个误区。

当使用此方法时,适配器会进行数据源的对比,如果同一个数据源中有更改,即执行刷新,否

则会执行方法但不会刷新列表,切记是更改数据源内容,哪怕是add或remove也不算。

Example:

 1     String[] list1 = new String[]{"test1-item"};
 2     String[] list2 = new String[]{"test2-item"};
 3     String[] list3 = new String[]{"test3-item"};
 4     String[] list4= list3;   
 5 
 6     list1 = new String[]{"new test1-item"};
 7     adapter1.notifyDataSetChanged();//无效  
 8 
 9     list2[0] = "new test2-item";
10     adapter2.notifyDataSetChanged();//有效
11 
12     list4[0] = "new test3-item";
13     adapter3.notifyDataSetChanged();//有效 

上述以数据来举例,当作为List数据时,同理。

 1     /** 按照postion重新排序*/
 2     public void doSort(){
 3         Collections.sort(infosList, new Comparator<Info>() {
 4 
 5             @Override
 6             public int compare(Info arg0, Info arg1) {
 7                 Info p1 = (Info) arg0;  
 8                 Info p2 = (Info) arg1;  
 9                 if (p1.sortPostion< p2.sortPostion)  
10                     return -1;  
11                 else if (p1.sortPostion== p2.sortPostion)  
12                     return 0;  
13                 else if (p1.sortPostion> p2.sortPostion)  
14                     return 1;  
15                 return 0; 
16             }
17         });
18         /** Info:实体类 {“title”, sortPostion}*/
19 //        infosList.add(new Info("new", 7));   无效
20         infosList.get(2).title = "change"; // 有效
21         adapter.notifyDataSetChanged();
22     }
23 很显然,重新排序后,事实上数据源的每一项值并没有更改,因此,直接刷新列表是无效的,即时add一项同样无效,测试发现,当
24 给其中某一项重新赋值后,列表刷新效果才会出来,但排序依然没有按照指针重新排列,只能重新给adapter重新addAll(List<Info>)才可以。


由于Java基础知识欠缺,因此并未明白为什么会这样日后看下底层代码再深究。

 

转载于:https://www.cnblogs.com/bbm7/p/4363562.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值