I have a multi-choice dialog that pops up when a button is clicked. The image below shows what it looks like.
Here is the problem. When I click on select all, I programmatically check all the items using listView.setItemChecked(position, true). And that part works. But after then, when user unchecks a specific items in the list, I want to uncheck select all.
Below is mycode, I don't know why it's not working.
private CharSequence[] itemList = {"select all", "one", "two", "three", "four", "five", "six"};
private boolean[] itemBooleanList = new boolean[]{false, false, false, false, false, false, false};
final AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
myDialog.setTitle("Select type(s)");
myDialog.setMultiChoiceItems(itemList, itemBooleanList, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
final ListView listView = ((AlertDialog)dialog).getListView();
if(indexSelected == 0){ // if "select all" is clicked - check/uncheck all items
for(int i=0; i<itemList.length; i++){
listView.setItemChecked(i, isChecked);
itemBooleanList[i] = isChecked;
}
}else{
itemBooleanList[indexSelected] = isChecked;
}
// now I check if all item in boolean[] are true or false, if one of the item is false, it returns false and `select all` can be unchecked
final boolean areAllTrue = areBooleanAllTrue(itemBooleanList);
listView.setItemChecked(0, areAllTrue);
System.out.println(Arrays.toString(itemBooleanList));
}
}).show();
PS: when I print itemBooleanList, if user unchecks an item, I do see that the boolean value at that index got set to false which means, logic is correct, it's just the setItemChecked that is not doing it's job.
Pls let me know if you want me to upload more code or screenshots.
I hope the following code will do the trick,
final ListView listView = ((AlertDialog)dialog).getListView();
if(indexSelected == 0){ // if "select all" is clicked - check/uncheck all items
for(int i=0; i<itemList.length; i++){
listView.setItemChecked(i, isChecked);
itemBooleanList[i] = isChecked;
}
}else{
itemBooleanList[indexSelected] = isChecked;
if(!isChecked) {
itemBooleanList[0] = false;
listView.setItemChecked(0, false);
}else{
//check whether all the items are checked otherthan 'select all'
//if true then
//itemBooleanList[0] = true;
//listView.setItemChecked(0, true);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With