[Android Develop] 解决 GridView/ListView 用 Adapter 于滑动时数据混乱的问题
发生范例
在 onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 下直接改变其 View 的属性时
会于滑动时产生混乱的情形,例如改变其背景颜色,被改变的内容于滑动时会乱跑到其他的 Item 上
ex: arg1.setBackgroundColor(Color.GREEN);
解决方式
将 onItemClick 中改变的 Code 写到 Adapter 上
ex (粗体为需注意的地方):
public class ImageAdapter extends BaseAdapter {
...
private ArrayList<Integer> selectList = new ArrayList<Integer>();
...
@SuppressLint("UseValueOf")
public void setSelection(int position) {
if(this.selectList.contains(new Integer(position))) {
this.selectList.remove(new Integer(position));
} else {
this.selectList.add(new Integer(position));
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
} else {
imageView = (ImageView) convertView;
}
...
...
if(this.selectList.contains(new Integer(position))) {
imageView.setBackgroundColor(Color.GREEN);
} else {
imageView.setBackgroundColor(Color.TRANSPARENT);
}
...
...
return imageView;
}
}