• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Creating an AlertDialog

AlertDialogs are pop ups used to prompt a user about an action to be taken. An AlertDialog may also be used for other actions such as providing a list of options to choose from or can be customized to have a user provide unique details such as their login information or application settings.

Creating alert dialog is very easy. An ALERTDIALOG is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:

  • A title
  • A text message
  • One, two, or three buttons
  • A list of selectable items (with optional checkboxes or radio buttons)
To create an AlertDialog, use the AlertDialog.Builder subclass. Get a Builder with AlertDialog.Builder(Context) and then use the class’s public methods to define all of the AlertDialog properties. After you’re done with the Builder, retrieve the AlertDialog object with create().

In this tutorial, let us discuss about creating different alert dialogues with one button(ok button), two buttons(yes or no buttons) and three buttons(yes, no and cancel buttons).

Check Snowflake Training here!
Android alert dialog with One button

The following code will create a simple alert dialog with one button. In the following code, setTitle() method is used for set Title to alert dialog. setMessage() is used for setting message to alert dialog. setIcon() is to set icon to alert dialog.

AlertDialog alertDialog = new AlertDialog.Builder(
AlertDialogActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to AndroidHive.info');

// Setting Icon to Dialog

alertDialog.setIcon(R.drawable.tick);

// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();

This output of about code will be like following image.

alert_1_button1.png

Source: Mindmajix
 
Last edited:
Back
Top Bottom