When a CheckBox is checked, I need to uncheck all other checkboxes and
store the index of a checked one
Here is my solution that came into my head right now. I don't now your implementation (implementation of Adapter, source of data etc.) so you will maybe need a little modifications. So now to my solution:
You need onCheckedChangedListener and put in into your ListAdapter class:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do your stuff
}
Now i don't know your actual scenario but most likely you have some collection of objects you are passing into Adapter and you're using it in getView() method that returns view of row.
Exactly here i suggest to modify your Object (item that represents each row in adapter) and add property:
private boolean isChecked;
that will "represent" your CheckBox.
Now implicitly each CheckBox will be unchecked (it's ok since booleans are implicitly assigned into false).
And now directly into Adapter class. In your class, exactly in your getView() you need to do following:
public View getView(final int position, View convertView, ViewGroup parent) {
RowHolder holder = null; // RowHolder that holds widgets for each row
LayoutInflater inflater = LayoutInflater.from(context); // for inflate rows
// logic for inflating rows, pretty simply
if (convertView == null) {
// inflate row
convertView = inflater.inflate(<yourLayout>, null, false);
holder = new RowHolder(convertView);
convertView.setTag(holder);
}
else {
// recycle row
holder = (RowHolder) convertView.getTag();
}
// inicialising row values
final Item i = collection.get(position); // item from collection
/** here will be work with CheckBoxes **/
// here you will set position as CheckBox's tag
holder.getCheckBox().setTag(position);
// set CheckBox checked or not due to item in collection
holder.getCheckBox().setChecked(item.isChecked());
// and assign listener to CheckBox
holder.getCheckBox().setOnCheckedChangeListener(this);
}
This is very immportant logic. Here you saved position of CheckBox in Adapter into CheckBox itself. Now CheckBox knows "where is located".
And then your listener will make following:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// buttonView is CheckBox you changed state so we know which CheckBox it is
int position = (Integer) buttonView.getTag();
// if CheckBox is checked
if (isChecked) {
// iterate collection and assign all items except selected into false
for (int i = 0; i < collection.size(); i++) {
if (i != position) {
collection.get(i).setChecked(false);
}
}
// now call notifyDataSetChanged() that will call getView() method again
// and it will update your List
notifyDataSetChanged();
}
}
Here listener will make a trick. Also there is something about
I hope it'll help you reach your goal.