Pages

Display Alert message in Android


How to display Alert message in Android Application?
Here is a sample code of an application that explains how you can display a simple Alert message in your Android application. The below code can be put on a button click event or wherever you would like it to popup.


             

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { /*DialogInterface called while setting the AlertDialog Buttons */
    public void onClick(DialogInterface dialog, int which) {
        
    //Here you can perform functions of Alert Dialog Buttons as shown


     switch (which){
        case DialogInterface.BUTTON_POSITIVE:
         //Yes button clicked
        break;


        case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
        break;
        }
     }
 };
       
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
 builder.setTitle("Alert Dialog");// Set the Title of Alert Dialog
 builder.setMessage("Are you sure?")
 .setPositiveButton("Yes",dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();/* Setting the Alert message with buttons Yes and No */                                                     



//You can also set the icon of Alert Dialog using this code
builder.setIcon(R.drawable.icon);