notifydatasetchanged(notifyDataSetChanged使用总结)

发布时间:2025-12-10 20:03:37 浏览次数:2

notifyDataSetChanged使用总结-notifydatasetchanged导致闪烁问题

notifyDataSetChanged使用总结在做客户端项目时,想使用notifidatasetchanged来刷新ListView,但是一直报错,ThecontentoftheadapterhaschangedbutListViewdidnotreceivea notification,先总结notifidatasetchanged使用要点如下:1.首先要包装adapter监视的数据是同一个对象

在做客户端项目时,想使用notifidatasetchanged来刷新ListView,但是一直报错,

The content of the adapter has changed but ListView did not receive a

notification,先总结notifidatasetchanged使用要点如下:


1.首先要包装adapter监视的数据是同一个对象,比如:
adapter = new SimpleAdapter(context, data, resource, from, to);
data只能是一个对象,否则notifidatasetchanged无效
2.data数据发生变化时,要及时用adapter.notifidatasetchanged来通知主线程刷新UI, 但不是每次改变都刷新 。比如: 正常情况下执行完data.clear() 要通知刷新UI,如果在一个方法里,data.clear() 只做初始化,接下来给data添加新数据,
则要在添加完之后通知。
3.如果涉及到网络请求,比如请求json数据并解析,然后更新解析数据显示在ListView上, 此时会创建子线程: new Thread (){
public void run(){
……….. } } 注意通知更新UI一定要放在主线程中执行。比如使用for循环给data添加数据: data.add()执行完之后,就使用消息处理机制发送请求: Message msg = new Message();
msg.what = CHANGE_UI;
handler.sendMessage(msg);
然后在主线程的Handler中如下刷新: private Handler handler = new Handler() {

public void handleMessage(android.os.Message msg) {

switch (msg.what) {

case CHANGE_UI:
adapter.notifyDataSetChanged();
break;
default:
break;
}

4.代码中已经使用了Adapter的notifyDataSetChanged()方法通知UI更新了,但是 还是会出现The content of the adapter has changed but ListView did not receive a
notification

。究其根本原因,还是线程之间同步的问题。比如,线程1更新了Adapter中的内容, 却还没有来得及通知内容已经更新,就又有线程2更新了Adapter中的内容,这个时候 如果线程1再通知内容更新,就会出现上述异常。

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477