In this post you will learn how to implement alertdialog in android, Android alertdialog used to
help users answer questions, confirm actions, read warning or error messages and make selections.
Android alertdialog is a floating window which popups in our activity screen.
Create new project in Android studio and name it ‘Dialog Demo’
1. Dialog with 1 Button:
The following code will create an alertdialog with Title, Message and a Positive button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//Creating alertdialog with 1 button. AlertDialog myDialog = new AlertDialog.Builder(YourActivity.this) //setting dialog title .setTitle("Your title") //setting dialog message .setMessage("Your message to users") //setting dialog uncancelable when user click outside the dialog .setCancelable(false) .setPositiveButton("Ok", (dialogInterface, i) -> { dialogInterface.dismiss(); }).create(); myDialog.show(); |
2. Dialog with 2 Button:
The following code will create an alertdialog with Title, Message and a Positive Negative button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//Creating alertdialog with 2 buttons. AlertDialog myDialog = new AlertDialog.Builder(YourActivity.this) //setting dialog title .setTitle("Confirm delete") //setting dialog message .setMessage("Do you really want to delete this") //setting dialog uncancelable when user click outside the dialog .setCancelable(false) //setting positive button confirm the action .setPositiveButton("Yes", (dialogInterface, i) -> { Toast.makeText(YourActivity.this, "Deleted", Toast.LENGTH_SHORT).show(); }) //setting negative button to cancel the action .setNegativeButton("Cancel", (dialogInterface, i) -> { dialogInterface.dismiss(); }).create(); myDialog.show(); |
3. Dialog with 3 Button:
The following code will create an alertdialog with Title, Message and a Positive, Negative and Neutral button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//Creating alertdialog with 3 buttons. AlertDialog myDialog = new AlertDialog.Builder(YourActivity.this) //setting dialog title .setTitle("Confirm delete") //setting dialog message .setMessage("Do you really want to delete this") //setting dialog uncancelable when user click outside the dialog .setCancelable(false) //setting positive button confirm the action .setPositiveButton("Yes", (dialogInterface, i) -> { Toast.makeText(YourActivity.this, "Deleted", Toast.LENGTH_SHORT).show(); }) //setting negative button to cancel the action .setNegativeButton("Cancel", (dialogInterface, i) -> { dialogInterface.dismiss(); }) //setting neutral button for neutral action .setNeutralButton("No idea", (dialogInterface, i) -> { dialogInterface.dismiss(); }).create(); myDialog.show(); |
That’s how we can create these kind of alertdialog application, alertdialog is an easy way to ask user for some permission or actions of user.