This is the second part of the How to a create a Dialog Box in Android tutorial. Follow this link - How to create a Dialog Box - Part 1, if you haven't read the first part and have directly landed here.

In this tutorial we will discuss the remaining two types of dialog boxes -

  • A dialog box containing a list
  • A dialog box containing checkboxes

Lets start with dialog box having a list in it. There is an onClick() function in the DialogBox.java. In this onClick() function we have a if condition to check whether Show List button has been clicked or not as shown below.

/** check whether the selectlist button has been clicked */

if (view == findViewById(R.id.selectlist)) {

//Code here to display the dialog box containing a list.

}

We will write our code inside this if condition to create and display the dialog box containing a list. For this we will use Builder sub-class of AlertDialog as we had in the previous two dialog boxes.

To create a list we will use setItem() method of this Builder sub class. The first argument of this setItem() function is an array containing the elements of the list that has to be created and the second argument is the click listener callback function that defines the action to take when the user selects an item. Check out the code given below -

/** check whether the selectlist button has been clicked */

if (view == findViewById(R.id.selectlist)) {

//List items

final CharSequence[] items = {"Milk", "Butter", "Cheese"};

//Prepare the list dialog box

AlertDialog.Builder builder = new AlertDialog.Builder(this);

//Set its title

builder.setTitle("Pick an item");

//Set the list items and assign with the click listener

builder.setItems(items, new DialogInterface.OnClickListener() {

// Click listener

public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();

}

});

AlertDialog alert = builder.create();

//display dialog box

alert.show();

}

On selecting a particular item the onClickListener() function will be called which in turn will display a toast notification containing the name of the selected item as shown in screenshots below.

Show List button in android
Dialog box with a list in android
Particular item being selected from the list in Android

Similarly for displaying a dialog box with checkboxes in it we use setSingleChoiceItems() method of the Builder sub class of AlertDialog. The first parameter of this method is again an array of items to be displayed. The second parameter is an integer value for the checkedItem, which indicates the zero-based list position of the default selected item and we use "-1" if don't want any item to be selected by default. The third parameter is the click listener function. Check out the code given below -

/** check whether the selectlistwithcheckbox button has been clicked */

if (view == findViewById(R.id.selectlistwithcheckbox)) {

//List items

final CharSequence[] items = {"Milk", "Butter", "Cheese"};

//Prepare the list dialog box

AlertDialog.Builder builder = new AlertDialog.Builder(this);

//Set its title

builder.setTitle("Pick an item");

//Set the list items along with checkbox and assign with the click listener

builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {

// Click listener

public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();

//If the Cheese item is chosen close the dialog box

if(items[item]=="Cheese")

dialog.dismiss();

}

});

AlertDialog alert = builder.create();

//display dialog box

alert.show();

}

Check out the screenshots shown below.

Show List with Checkboxes button in Android
Dialog Box with checkboxes in Android
Choosing a particular item from list in Android

In the onClickListener() function we have introduced an if condition which checks whether the selected item is Cheese and if it is so we have called a function dialog.dimiss(). This function closes/dismisses the dialog box. Apart from this everything is similar to the code of the previous dialog box i.e. whenever an item is selected the toast notification displays the selected item's name.

An item being selected in a listin dialog box in Android
Toast Notification is displayed after selecting a particular option in Android

So now the complete code of DialogBox.java will be -

package com.botskool.DialogBox;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class DialogBox extends Activity implements OnClickListener{
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       /** We need to set up a click listener on the alert button */
       Button alert = (Button) findViewById(R.id.alertbutton);
       alert.setOnClickListener(this);
       /** We need to set up a click listener on the yesno button */
       Button yesno = (Button) findViewById(R.id.yesnobutton);
       yesno.setOnClickListener(this);
       /** We need to set up a click listener on the selectlist button */
       Button selectlist = (Button) findViewById(R.id.selectlist);
       selectlist.setOnClickListener(this);
       /** We need to set up a click listener on the selectlistwithcheckbox button */
       Button selectlistwithcheckbox = (Button) findViewById(R.id.selectlistwithcheckbox);
       selectlistwithcheckbox.setOnClickListener(this);
   }

   public void onClick(View view) {
       /** check whether the alert button has been clicked */
       if (view == findViewById(R.id.alertbutton)) {
            // Create the alert box
           AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
           // Set the message to display
           alertbox.setMessage("This is an alert box.");
           // Add a neutral button to the alert box and assign a click listener
           alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
               // Click listener on the neutral button of alert box
               public void onClick(DialogInterface arg0, int arg1) {
                   // The neutral button was clicked
                   Toast.makeText(getApplicationContext(), "'OK' button clicked", Toast.LENGTH_LONG).show();
               }
           });
            // show the alert box
           alertbox.show();
       }
        /** check whether the yesno button has been clicked */
       if (view == findViewById(R.id.yesnobutton)) {
           // Create the dialog box
           AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
           // Set the message to display
           alertbox.setMessage("This is a dialog box with two buttons");
            // Set a positive/yes button and create a listener
           alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               // Click listener
               public void onClick(DialogInterface arg0, int arg1) {
                   Toast.makeText(getApplicationContext(), "'Yes' button clicked", Toast.LENGTH_SHORT).show();
               }
           });
           // Set a negative/no button and create a listener
           alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
               // Click listener
               public void onClick(DialogInterface arg0, int arg1) {
                   Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
               }
           });
           // display box
           alertbox.show();
       }
       /** check whether the selectlist button has been clicked */
       if (view == findViewById(R.id.selectlist)) {
           //List items
           final CharSequence[] items = {"Milk", "Butter", "Cheese"};
           //Prepare the list dialog box
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
           //Set its title
           builder.setTitle("Pick an item");
           //Set the list items and assign with the click listener
           builder.setItems(items, new DialogInterface.OnClickListener() {
               // Click listener
               public void onClick(DialogInterface dialog, int item) {
                   Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
               }
           });
           AlertDialog alert = builder.create();
           //display dialog box
           alert.show();
       }
       /** check whether the selectlistwithcheckbox button has been clicked */
       if (view == findViewById(R.id.selectlistwithcheckbox)) {
           //List items
           final CharSequence[] items = {"Milk", "Butter", "Cheese"};
           //Prepare the list dialog box
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
           //Set its title
           builder.setTitle("Pick an item");
           //Set the list items along with checkbox and assign with the click listener
           builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
               // Click listener
               public void onClick(DialogInterface dialog, int item) {
                   Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
                   //If the Cheese item is chosen close the dialog box
                   if(items[item]=="Cheese")
                       dialog.dismiss();
               }
           });
           AlertDialog alert = builder.create();
           //display dialog box
           alert.show();
       }
   }
}

This concludes our tutorial. Don't forget to post your doubts, queries or suggestions in our forum. Download DialogBox.apk.