How to create alert dialog in Android Studio using Java?
Alert dialog are shown to users in an Android application to do an action based on the users’ selection. An alert dialog typically contains a Yes and No buttons, or continue and cancel buttons. Based on the selection by the user. The application can perform further actions.
Below is the code to create an alert dialog,
// Code for displaying alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(“Message to be displayed on alert box“)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Your code to handle Yes button click
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Your code to handle No button click
}
});
// Create the AlertDialog
builder.create();
// Show the Dialog
builder.show();
// Imports for the above code
import android.app.AlertDialog;
import android.content.DialogInterface;
In the above code,
- The alert dialog shows the message “Message to be displayed on alert box”.
- It has a positive button with text as “Yes”.
- It has a negative button with text as “No”.
If you like my articles, please follow me. You can also support me by https://www.buymeacoffee.com/akarshseggemu