Home Tutorials Hints & Tips

Getting Started in Android Development

Part 42 - The Alert Dialog

In this tutorial we will look at a basic Android Dialog box example. In particular, we will look at the alert dialog that prompts a user to select one of two actions. There are essentially two types of dialog box. The alert dialog and the DatePickerDialog or TimePickerDialog.

Android Dialog Screenshot

AlertDialog can contain up to three buttons and the designer has control over the dialog title [1], the content area [2] and action buttons [3]. The content area can contain textural information or a custom layout. More information about dialog box design can be found here.

In our simple example the dialog box is called when a "delete data" button is clicked from a simple layout. The code for the dialog box is called from a private method that we will create. Therefore, we only need one line of code shown below in the onClick() method for the button.

openAlertDialog();

We can now turn our focus to the openAlertDialog() method. We first need to build or design our dialog box, define the actions of the buttons and the show dialog box. To build the dialog box we use the AlertDialog.Builder class. The first three lines of code define the contents of the dialog box, it's purposes and the instructions we will offer the user.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Delete this Data");
alertDialogBuilder.setMessage("Are you sure?");

We then define an onClickListenser for each of the buttons. We will have "positive" and "negative" buttons. If we had a third button this would be a "neutral button". Our positive text will be "yes" and our negative text will be "no"

alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {

      //code for positive action

   }
});

alertDialogBuilder.setNegativeButton("no", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {

      //code for negative action

   }
});

In our tutorial, rather than perform any specific action on the button clicks, we will simply show an appropriate toast.

The final two lines of code create the dialog box from the information held in the builder and then show the dialog box.

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

As screenshot of the resultant dialogue box is shown below.

Android Dialog Screenshot

After this tutorial your DialogActivity.java should look similar to the one below:

Your activity_dialog.xml file should look similar to the one below:

Your MainActivity.java file should look similar to the one below:

Your AndroidManifest file should look similar to the one below:


Download Download tutorial set 3

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved