How do I display an alert dialog on Android?
android, android-alertdialog, android-dialog
Solution
You could use an `AlertDialog` for this and construct one using its `Builder` class. The example below uses the default constructor that only takes in a `Context` since the dialog will inherit the proper theme from the Context you pass in, but there's also a constructor that allows you to specify a specific theme resource as the second parameter if you desire to do so.
new AlertDialog.Builder(context)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete operation
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
Problem
I want to display a dialog/popup window with a message to the user that shows "Are you sure you want to delete this entry?" with one button that says 'Delete'. When `Delete` is touched, it should delete that entry, otherwise nothing. I have written a click listener for those buttons, but how do I invoke a dialog or popup and its functionality?
Related problems
- How to implement a confirmation (yes/no) DialogPreference?
- Android simple alert dialog
- Android Alert Dialog with one, two, and three buttons
- DialogFragment advantages over AlertDialog
- How to create a popup window (PopupWindow) in Android
- Android DialogFragment vs Dialog
- Android dialog disappears on its own