How To Implement Alert Dialog In Android

How To Implement Alert Dialog In Android
Android Developers need a way for prompting user to take a decision without which the app cannot proceed its process. For this AlertDialog was introduced. Alert Dialogs are simple way of prompting users. So today in this tutorial we will be learning "How to implement Alert Dialog in Android".

Download Project

Why The Hell Do We Use Alert Dialog?

According to Android Developers Website, Alert Dialogs must be used to prompt users to take decision/actions without which the process cannot progress. For example, Alert Dialogs can be used to prompt user about No Internet Connectivity, or can be used to select an option from list of options, or for confirming any critical actions like deleting a file.

What Will It Look Like?


Understanding Alert Dialog

Alert Dialogs are very simple implementation wise. When we want to display an Alert Dialog, just create and initialise AlertDialog.Builder object. Then using that object we can set title and message for the dialog. We can also add maximum three buttons to the dialog. There are many other options too, which will be explained below in this tutorial. Whenever we add a button to a dialog, we also need to set an OnClickListener to it. This allows use to perform specific actions when user clicks on any of the buttons.

Add Alert Dialog With One Button

Add Alert Dialog With One Button
In this below code, we have used several methods that I will be explaining. Firstly, we have used setTitle() method which is used to set the title of the Alert Dialog. Second method that we have used is the setMessage() method which is used to set the message for the dialog. Another method that to be explained is the the show() method. This method is used to display the dialog to the user.
//Firstly, create a AlertDialog object
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
//Set the title of the dialog using setTitle() method.
alertDialog.setTitle("This is Title");
//Set the message in the dialog using the setMessage() method.
alertDialog.setMessage("This is a message!");
//Set the button in the dialog using setButton() method.
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        //Write your action code here
        Toast.makeText(MainActivity.this, "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});
//show() method is used to display the dialog
alertDialog.show();

Here in this code, we use the setButton() method to add a single button to the dialog. This method takes three parameters.

Explaining the Parameters of setButton() method

1. int whichTypeOfButton (First Parameter): There are three contstants already defined inside AlertDialog class. So we can use the AlertDialog.BUTTON_POSITIVE to set the button as positive button or we can use the AlertDialog.BUTTON_NEGATIVE to set the button as negative button or we can use the AlertDialog.BUTTON_NEUTRAL to set the button as neutral button.

2. CharSequence text (Second Parameter): This is nothing but the String parameter. This parameter will be used as text for the button.

3. OnClickListener listener (Third Parameter): This parameters is used to set an OnClickListener to the button that we add to the dialog. Inside this listener we will define the action that will be performed when that button is clicked.

Add Alert Dialog With Two Buttons

Add Alert Dialog With Two Button

Here in this code, we have used two methods to add buttons. First is setPositiveButton() method which is used to set the positive button for dialog. and second method is setNegativeButton() method which is used to set the negative button for dialog. Both this methods take first parameter as String text which will be used to set the text of the button and second parameter is an OnClickListener object to perform specific action.
//Firstly, create a AlertDialog.Builder object
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
//Set the title of the dialog using setTitle() method.
alertDialog.setTitle("This is Title");
//Set the message in the dialog using the setMessage() method.
alertDialog.setMessage("This is a message!");
//Set the Positive Button "YES"
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        //Write your action code here
        Toast.makeText(MainActivity.this, "You clicked on YES", Toast.LENGTH_SHORT).show();
    }
});
//Set the Negative Button "NO"
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        //Write your action code here
        Toast.makeText(MainActivity.this, "You clicked on NO", Toast.LENGTH_SHORT).show();
    }
});
//show() method is used to display the dialog
alertDialog.show();

Add Alert Dialog With Three Buttons

Add Alert Dialog With Three Button

Here in this code, we use the same two methods for adding the buttons as used in the Alert Dialog with two buttons. And for adding third button we use the setNeutralButton() method.
//Firstly, create a AlertDialog.Builder object
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
//Set the title of the dialog using setTitle() method.
alertDialog.setTitle("This is Title");
//Set the message in the dialog using the setMessage() method.
alertDialog.setMessage("This is a message!");
//Set the Positive Button "YES"
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        //Write your action code here
        Toast.makeText(MainActivity.this, "You clicked on YES", Toast.LENGTH_SHORT).show();
    }
});
//Set the Negative Button "NO"
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialogInterface, int i) {
       //Write your action code here
       Toast.makeText(MainActivity.this, "You clicked on NO", Toast.LENGTH_SHORT).show();
   }
});
//Set the Neutrol Button "CANCEL"
alertDialog.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        //Write your action code here
        Toast.makeText(MainActivity.this, "You clicked on Cancel", Toast.LENGTH_SHORT).show();
    }
});
//show() method is used to display the dialog
alertDialog.show();

Concept Of Positive, Negative And Neutral Button

While learning in this tutorial, you might have thought that why are there separate methods for positive, negative and neutral buttons. The main reason for this is the positioning of buttons inside the dialog. Remember, we did not specify any position for buttons, whether where they will be placed. They would automatically be added to there place irrespective of the sequence of declaration. Android OS has standard of positioning those buttons in different positions in different versions.
For example:

  1. On devices running Honeycomb or older version, the buttons order is POSITIVE - NEUTRAL - NEGATIVE from left to right.
  2. On devices running new Holo interface, the buttons order is NEGATIVE - NEUTRAL - POSITIVE from left to right.
  3. On devices running newer versions of android, the buttons order is NEUTRAL - NEGATIVE - POSITIVE from left to right.

What Else?

AlertDialog is not limited to this methods only. There are more such methods for customizing the dialog. I will be posting more such tutorials that will help you customize the AlertDialog. But for now lets see some useful methods.
1. setIcon(int resID): This method is used to set an icon for the AlertDialog. It takes drawable resource id as parameter. Example: alertDialog.setIcon(R.drawable.ic_launcher);
Add Alert Dialog With Icon Before Title

2. setCancelable(boolean cancel): This method specifies whether the dialog should be dismissed if the user clicks on the BACK key. This method takes a boolean value.

3. setCanceledOnTouchOutside(boolean cancel): This method is used to specify whether the dialog will be dismissed if the user touches some where outside the dialog. This method takes a boolean value.

Wooohoo! It's done. Now you are ready to prompt your user with this alert dialogs.

1 comment:

  1. Nice Post Admin. Was Looking for such Clear cut explanation.

    ReplyDelete