Monday, 12 October 2015

creating a multi select dialog box in android

  1. Create a java Activity class where you want your dialog to appear. 
  2. Create a field     private ArrayList mSelectedItems; for storing your array list.
  3. Call launchAddItems() when you need to create the dialog.
     
  4. Add the following function to create the dialog protected void
  5.  launchAddItems() {
              mSelectedItems = new ArrayList();
              final String items[] = {"Android","Iphone","Nokia"};

              AlertDialog.Builder ab=new AlertDialog.Builder(this);
              ab.setTitle("Dialog Title")
              .setMultiChoiceItems(items, null,  new DialogInterface.OnMultiChoiceClickListener(){

                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    if (isChecked){
                          mSelectedItems.add(which);
                    }
                    else if(mSelectedItems.contains(which)){
                        mSelectedItems.remove(Integer.valueOf(which));
                    }
                }
                 
              }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int id) {
                      // User clicked OK, so save the mSelectedItems results somewhere
                      // or return them to the component that opened the dialog
                  }
              }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int id) {
                  }
              });

              ab.create();;
             
           
              ab.show();       
        }

No comments:

Post a Comment