标签:
Adapter的数据自己要用于getView和getCount,而且程序是getCount后在不同方法里面连续getView,这带来个问题:getCount后,数据被其他线程删除,在getView的时候越界
public class ConcurrentAdapter<T> {
//用于外部操作的List,外部对其增删
private List<T> objectsCached=new ArrayList<T>();
//用于Adapter内部计算用,从外部Copy过来
private List<T> objects=new ArrayList<T>();
//用于缓存List的数量,当-1的时候,表示外部修改过List,需要更新
private int count=-1;
public int getCount(){
if(count==-1){
synchronized (objectsCached){
objects.clear();
objects.addAll(objectsCached);
count=objects.size();
return count;
}
}else{
return count;
}
}
public T getObject(int position){
return objects.get(position);
}
public void addObject(T object){
synchronized (objectsCached){
objectsCached.add(object);
count=-1;
}
}
public void addObjects(List<T> objects){
synchronized (objectsCached){
objectsCached.addAll(objects);
count=-1;
}
}
public void setObjects(List<T> objects){
synchronized (objectsCached){
objectsCached.clear();
objectsCached.addAll(objects);
count=-1;
}
}
public void removeObject(T object){
synchronized (objectsCached){
objectsCached.remove(object);
count=-1;
}
}
}
标签:
原文地址:http://blog.csdn.net/dzg1977/article/details/44924993