在Android开发过程中,使用ListView时,发现这个错误偶尔会出现。特别是做压力测试的时候,不停的点击刷新,更容易出现这个错误。
在网上找了一下关于这个问题的解决办法,说的是直接备份一份数据源,我根据他们说的,办法是可行的,上代码。
public void setDataList(ArrayList<Map<String, Object>> dataList) { if (dataList != null) { mDatas = (List<Map<String, Object>>) dataList.clone(); notifyDataSetChanged(); } } public void clearDataList() { if (mDatas != null) { mDatas.clear(); } }
在刷新的时候,调用setDataList()方法,这只是一种迂回的方法,后来发现本质的原因,还是因为在刷新适配器的时候,调用接口之前,清空了数据源的内容,然后再填充适配器,导致的数据源与适配器不匹配。上代码。if (mNotificationAdapter == null) { mNotificationAdapter = new AdpFragNotificationList(mActivity); mNotiSwipeView.setAdapter(mNotificationAdapter); } mNotificationAdapter.setDataList(mNotiList);
mPromotionSwipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mPromotionList.clear(); getDataList(false, 0); } });只需要将数据源中的清除放到更新适配器前清除即可。