I want the user to confirm an action by showing them a dialogue with a message and "yes" or "no" buttons. How can I make that appear, and perform actions based on the button they pick?
Thanks, AlertDialog looks like what I'm looking for. But, there's an error where it says "AlertDialog.Builder(this);"
that tells me, "The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined"
–
As shown here :
private static final int DIALOG = 1;
to show the dialog call
showDialog(DIALOG);
override onCreateDialog, check with a switch for the dialog ID and insert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure about this?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// whatever if YES
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// whetever if NO
}
});
AlertDialog alert = builder.create();
What you're looking for is an AlertDialog
. Using the example here , you can easily create a Yes/No dialog that will look something along the lines of:
You create a new AlertDialog.Builder
, pass it some parameters, finally invoke its create()
method and assign the return value to an AlertDialog
object to hold a reference to it.
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Question");
adb.setMessage(Html.fromHtml("Visit Stackoverflow?"));
adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Action for YES
startActivity(
new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://www.stackoverflow.com")));
return;
}
});
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Action for NO
return;
}
});
AlertDialog myDialog = adb.create();
it's simple as below
new AlertDialog.Builder(this)
.setTitle("Info")
.setMessage("hello")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Some stuff to do when ok got clicked
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Some stuff to do when ok got clicked
}
})
.show();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.