Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A list with multi-select Checkbox on an Alert Dialog?

I have been trying to get a list with some 10-12 items having a checkbox each on an alert dialog (i.e. when my activity starts). So far I have come up with the following code; it doesn't have the checkboxes in it.
So, how can I implement this? Any sample code or advice will be appreciated.
Thanks

final CharSequence[] items = {"cat1","cat2","cat3" };
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setTitle("Categories");
          builder.setItems(items, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int item) {
            switch (item) {
            case 0:
             //handle item1
             break;
            case 1:
             //item2
             break;
            case 2:
             //item3
             break;
            default:
             break;
            }  }
          });
          AlertDialog alert = builder.create();
          alert.show();
like image 926
beerBear Avatar asked Dec 19 '12 08:12

beerBear


2 Answers

You have to set setSingleChoiceItems() methods in builder object instead of setItems like below.

 builder.setSingleChoiceItems(items , -1,
                      new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
               // The 'which' argument contains the index position
               // of the selected item
           }
    })

If you want to display multiple selection list dialog then you have to set setMultiChoiceItems() instead of setSingleChoiceItems with DialogInterface.OnMultiChoiceClickListener in its argument

All things are mention in Developer.Android.com you can look for a dialog help here

like image 150
rajpara Avatar answered Nov 14 '22 11:11

rajpara


I recomend not to use complicated custom view in alert dialog. Better use start activity for result for this. In manifest set android:theme="@style/Theme.Dialog" for your dialog activity

like image 41
Artem Zelinskiy Avatar answered Nov 14 '22 10:11

Artem Zelinskiy