Dialogue Fragment With Multiple Selection In Android

Introduction

 
Dialogues are most commonly used in Android to show some messages to the user or to get some confirmation from the user. In some cases, we need to show a dialogue where a user needs to select more than one option.
 
There are two ways to create dialogues; they are DialogueFragment and Dialogue. Builder class. A Dialogue will normally look as shown below,
 
 
Here I am going to describe how to display a multiple selection dialogue in an activity. For that I am using a dialogueFragment and this has the life cycle methods as onCreate(),onCreateDialogue(),onCreateView(). In the older methods onCreateDialogue() you can construct your dialogue. But with DialogueFragment you can create this on onCreateView()
 
I have declared a string array in the values folder that contains the options in the dialogue box
 
Here I have an activity, in that activity, I create a button, on clicking that button it will show a dialogue with multiple options and each option has a checkbox a the right side of it.
 
For Alert dialogue, I created a custom class named MyAlert that extends from DialogueFragment. And in the onCreateDialogue() please add the code
  1. public Dialog onCreateDialog(Bundle savedInstanceState)    
  2. {    
  3.     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());    
  4.     builder.setTitle("Title here");    
  5.     builder.setMultiChoiceItems(R.array.titles, nullnew DialogInterface.OnMultiChoiceClickListener()     
  6.     {    
  7.         @Override    
  8.         public void onClick(DialogInterface dialogInterface, int i, boolean b)    
  9.         {    
  10.             Toast.makeText(getActivity(), "item clicked at " + i, Toast.LENGTH_SHORT).show();    
  11.         }    
  12.     });    
  13.     Dialog dialog = builder.create();    
  14.     return dialog;    
  15. }   
    The builder.setMultiChoiceItems add the arrays which I declared earlier as the choicelist, and on selecting each option a Toast message will be displayed with the index of that option. The output will be like the following.
     
     
    Read more articles on Android


    Similar Articles