How to display a Yes/No dialog box on Android? How to display a Yes/No dialog box on Android? android android

How to display a Yes/No dialog box on Android?


AlertDialog.Builder really isn't that hard to use. It's a bit intimidating at first for sure, but once you've used it a bit it's both simple and powerful. I know you've said you know how to use it, but here's just a simple example anyway:

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        switch (which){        case DialogInterface.BUTTON_POSITIVE:            //Yes button clicked            break;        case DialogInterface.BUTTON_NEGATIVE:            //No button clicked            break;        }    }};AlertDialog.Builder builder = new AlertDialog.Builder(context);builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)    .setNegativeButton("No", dialogClickListener).show();

You can also reuse that DialogInterface.OnClickListener if you have other yes/no boxes that should do the same thing.

If you're creating the Dialog from within a View.OnClickListener, you can use view.getContext() to get the Context. Alternatively you can use yourFragmentName.getActivity().


Try this:

AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("Confirm");builder.setMessage("Are you sure?");builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {    public void onClick(DialogInterface dialog, int which) {        // Do nothing but close the dialog        dialog.dismiss();    }});builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        // Do nothing        dialog.dismiss();    }});AlertDialog alert = builder.create();alert.show();


Steve H's answer is spot on, but here's a bit more information: the reason that dialogs work the way they do is because dialogs in Android are asynchronous (execution does not stop when the dialog is displayed). Because of this, you have to use a callback to handle the user's selection.

Check out this question for a longer discussion between the differences in Android and .NET (as it relates to dialogs):Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)