AlertDialog MultiChoiceItems Listener problems
Asked Answered
A

4

7

I am currently using the AlertDialog.builder to create a multichoice list for the user (checkboxes). This works great, except we want one of the buttons to deselect all of the others in the list.

builder.setMultiChoiceItems(list, checked,
  new DialogInterface.OnMultiChoiceClickListener() {
   public void onClick(DialogInterface dialog,
     int item, boolean isChecked) {

    if(item == ANY_ITEM_BUT_0)
    {

     ((AlertDialog) dialog).getListView().setItemChecked(0, false);

    }
   }
  });

When using "true" it will successfully check the box, but when using false it does not uncheck it (unless i have manually set it to true before hand.) Is there a separate listener I should be using to detect when a user clicks these? It seems to me that there are two checkmarks set, one by the "setItemChecked(0, true);", and one by actually selecting it.

This has been driving me nuts for a couple days now, any help would be greatly appreciated.

Anglo answered 28/10, 2009 at 23:29 Comment(0)
N
8

OH!!! I forget it to ensure deselect you must change checked to null ;), I had the same issue.

    builder.setMultiChoiceItems(list, null, new DialogInterface.OnMultiChoiceClickListener() {
...
Niles answered 20/1, 2010 at 21:18 Comment(1)
You have saved me a lot of time :) Thanks! I was setting all items with false, but it seems that null is all i needed!Caudex
N
3

To deselect the other items it works fine::

if(item == ANY_ITEM_BUT_0){    
   for(int i=0; i<items.length;i++){  
            if (item != ANY_ITEM_BUT_0)                             
           ((AlertDialog)dialog).getListView().setItemChecked(i, false);
    }
}
Niles answered 20/1, 2010 at 19:55 Comment(0)
G
1

Dont think you can change the values in the list since the list-items (checkboxes) are controlled by the builder-object. However, you could simply make the dialog re-initiate when the first item is clicked... by dismissing the dialog that is showing, and create a new one....

Glasgo answered 27/11, 2009 at 22:49 Comment(0)
S
0

If you want to set a check box to not be checked and you need to set the checkedItems array on the call to setMultiChoiceItems(), you need to set the checked array items to false as well. Make sure your checked array is final so you can access it in the listener.

builder.setMultiChoiceItems(list, checked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
 int item, boolean isChecked) {

if(isChecked && item == ANY_ITEM_BUT_0)
{
   for(int i=0; i<list.length;i++){  
      if (i != ANY_ITEM_BUT_0) {   
       checked[i] = false;                          
       ((AlertDialog)dialog).getListView().setItemChecked(i, false);
        } 
     }
   }
  }
});
Spallation answered 6/10, 2013 at 18:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.