Saturday, October 1, 2011

Using multiselect list with a dialog

AlertDialog is a versatile dialog. It can be used even for displaying a list where multiple values can be checked.

First you create a alertdialog.
AlertDialog.Builder  d = new AlertDialog.Builder(yourcontext);


Next you create the array which holds the items to be displayed

 String elements [] = {"Burger","Pizza","Cake","Coke","Fruits"};


Next you add multichoiceitems to the dialog

d.setMultiChoiceItems(elements, null , new OnMultiChoiceClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which, boolean isChecked) {
       if(isChecked){
          String str = elements[which];
          Toast.makeText(youractivity.this,
                    "you have selected"+str,
                     Toast.LENGTH_LONG).show();
        }
   }
 });
d.setPositiveButton("Save", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
yourOnClickMethod();
   }
});
d.show();
Now our dialog looks something like this





 The second parameter to setMultiChoiceItems is a boolean array, which will have true for all items which must be checked. If you do not want any to be checked, it can be null as we have used.
e.g
boolean selected[]= {true,false,false,true,true};
d.setMultiChoiceItems(elements,selected,
new OnMultiChoiceClickListener(){
                    --------
                    -------
});
With this modification, initially first, fourth and fifth items will be checked.

 

No comments:

Post a Comment