I got a SimpleCursor Adapter for a ListView and want to implement a Checkbox. Everything works fine except that the Checkbox is randomly (mirrored) checked on my ListView. I know it has to do with recycled ListView rows, but I can't get it to work. Here is my code:
private void displayListView() {
Cursor cursor = dbHelper.fetch...
// The desired columns to be bound
String[] columns = new String[] {
ProduktAdapter.KEY_CODE,
ProduktAdapter.KEY_NAME,
ProduktAdapter.KEY_CONTINENT,
ProduktAdapter.KEY_REGION,
ProduktAdapter.KEY_PHOTO
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code,
R.id.name,
R.id.continent,
R.id.region,
R.id.list_image
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.produkt_info,
cursor,
columns,
to,
0);
dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (view.getId() == R.id.list_image) {
String _name = cursor.getString(columnIndex);
File file = new File(Environment.getExternalStorageDirectory()
.......
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
((ImageView) view).setImageBitmap(bitmap);
return true;
} else {
return false;
}
}});
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(dataAdapter);
I got a CHOICE_MODE_MULTIPLE layout, and tried to save the Checkbox State to an array, (with getView) but still dont get it working. (Something like that):
public View getView(final int pos, View inView, ViewGroup parent) {
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(R.layout.kuehlschrankliste, null);
}
final CheckBox cBox = (CheckBox) inView.findViewById(R.id.check);
cBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(cBox.isChecked()) {
itemChecked.set(pos, true);
// do some operations here
}
else{
itemChecked.set(pos, false);
// do some operations here
}
}
});
cBox.setChecked(itemChecked.get(pos));
return inView;
}