Android AlertDialog Example

Android alert dialog is a window which prompts while the user is doing some action. Mostly the dialog will consist of two button named OK or CANCEL and a message which is decision making on something. Apart from that android is allowing to add some widget like EditText to alert dialog to get some values  from the user based on the requirement and it is possible to give 3 buttons as well if there is more action to do. In this tutorial we will see how to implement a simple alert dialog with two buttons.

It is as simple as adding the following method to your activity,s java file and call this method in your button click or whenever you want.

public void CreateAlertDialog() {
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

alertbox.setTitle("Title");
alertbox.setMessage("Alert Dialog message will comes here");

alertbox.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {

// will automatically dismiss the dialog and will do nothing
}
});


alertbox.setPositiveButton("OK",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {

// do your action
}
});
alertbox.show();
}

You will get the following output once you run the code

alert-dialog-android
alert-dialog-android

Now let us see how to implement AlertDialog with 3 buttons .It is as simple as adding one more button “Neutral”. Here i am showing the example for alert dialog with 3 button – Edit,Delete,Cancel

Just Replace the above method on button click with the below code.

public void CreateAlertDialog() {
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

alertbox.setTitle("Title");
alertbox.setMessage("Alert Dialog message will comes here");

alertbox.setNegativeButton("EDIT",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {

// do edit action
}
});

alertbox.setNeutralButton("CANCEL",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {

// will automatically dismiss the dialog and will do nothing
}
});
alertbox.show();


alertbox.setPositiveButton("DELETE",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {

// action for delete
}
});
alertbox.show();
}

output

alert-dialog-3-buttons
alert-dialog-3-buttons

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *