Wednesday 23 April 2014

Android AlertDialog example: Custom MultiChoiceItem with "Select All" option

If you want to set the MultiChoiceItem in your AlertDialog and you want to add "Select All" option, this is an example code for you.

I was aiming for this:



So, here it is: activity_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity" >  
   <Button  
     android:onClick="onDialog"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="Show Dialog" />  
 </LinearLayout>  

And this is our array.xml file in resources that we will use for our list:

 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
   <string-array name="items">  
     <item >Select all</item>  
     <item >First</item>  
     <item >Second</item>  
     <item >Third</item>  
     <item >Fourth</item>  
   </string-array>  
 </resources>  

And finally, MainActivity.java in which the magic happens. Main things are AlertDialog.Builder.setMultiChoiceItems(R.array.items, null, null) and listView.setOnItemClickListener(...), because these two things combined give us a possibility to have a "Select All" option.

 public class MainActivity extends Activity {  
     AlertDialog mDialog = null;  
     /**  
      * This becomes false when "Select All" is selected while deselecting some other item on list.  
      */  
     boolean selectAll = true;   
     /**  
      * Number of items in array list and eventually in ListView  
      */  
     int length;  
     @Override  
     protected void onCreate(Bundle savedInstanceState) {  
         super.onCreate(savedInstanceState);  
         setContentView(R.layout.activity_main);  
         length = getResources().getStringArray(R.array.items).length;  
     }  
     public void onDialog (View v) {  
         mDialog = onCreateDialog(null);          
         mDialog.show();  
         // we get the ListView from already shown dialog  
         final ListView listView = mDialog.getListView();  
         // ListView Item Click Listener that enables "Select all" choice  
         listView.setOnItemClickListener(new OnItemClickListener() {  
             @Override  
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
                 boolean isChecked = listView.isItemChecked(position);  
                 if (position == 0) {  
                     if(selectAll) {  
                         for (int i = 1; i < length; i++) { // we start with first element after "Select all" choice  
                             if (isChecked && !listView.isItemChecked(i)   
                                     || !isChecked && listView.isItemChecked(i)) {  
                                 listView.performItemClick(listView, i, 0);      
                             }  
                         }          
                     }  
                 } else {      
                     if (!isChecked && listView.isItemChecked(0)) {  
                         // if other item is unselected while "Select all" is selected, unselect "Select all"   
                         // false, performItemClick, true is a must in order for this code to work  
                         selectAll = false;  
                         listView.performItemClick(listView, 0, 0);          
                         selectAll = true;  
                     }  
                 }  
             }  
         });  
     }  
     public AlertDialog onCreateDialog(Bundle savedInstanceState) {  
       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);  
       // Set the dialog title  
         builder.setTitle(R.string.dialog)  
             // Specify the list array, the items to be selected by default (null for none),  
             // and the listener is null in order to "Select all" choice to work  
             .setMultiChoiceItems(R.array.items, null, null)  
             // Set the action buttons  
         .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {  
             @Override  
             public void onClick(DialogInterface dialog, int id) {  
               // User clicked OK, so save something here  
              }  
           })  
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {  
              @Override  
              public void onClick(DialogInterface dialog, int id) {}  
           });  
       return builder.create();  
     }  
 }  

Hope you've enjoyed in this code example!

Cheers!

2 comments: