beerBear
beerBear

Reputation: 979

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();

Upvotes: 9

Views: 7114

Answers (3)

Ali Obeid
Ali Obeid

Reputation: 141

As rajpara said, but I don't forget to have less complexity in your code by replacing your switch to items[which].toString();

Upvotes: 0

rajpara
rajpara

Reputation: 5203

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

Upvotes: 5

Artem Zelinskiy
Artem Zelinskiy

Reputation: 2210

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

Upvotes: 1

Related Questions