[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;
}
}