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

17

390

Yes, I know there's AlertDialog.Builder, but I'm shocked to know how difficult (well, at least not programmer-friendly) to display a dialog in Android.

I used to be a .NET developer, and I'm wondering is there any Android-equivalent of the following?

if (MessageBox.Show("Sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes){
    // Do something...
}
Therianthropic answered 19/3, 2010 at 15:32 Comment(3)
#2029197Pappas
How do i resue AlertDialog code and handle events(yes, no actions) in all the screens? In .Net we use the Action class to handle the events, is there any way to implement this? I know using interfaces we can do this but any alternate way?Dumbstruck
Yes.... we .NET developers really do have a hard time with android....I wonder if Xamarin is a great tool?Sociometry
T
796

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().

Thwack answered 19/3, 2010 at 15:50 Comment(15)
new AlertDialog.Builder(this); Compile time error: 'The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined'Widespread
if i want to dismiss that dialog box, what should write under case DialogInterface.BUTTON_NEGATIVE case.Steelman
@VijayBagul dialog.dismiss();Gimmick
Simple and useful, btw, dialog will dismiss itself after user click "YES" or "NO" button. There is nothing you need to do.Texture
Me myself, I have used it lots of times. But I have found it is actually easier and faster to look it up on SO. The code sample given here is so simple...I really wish Android documentation would look like this.Coarsegrained
@EricLeschinski probably "this" isn't a context, try this one: AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext());Conn
im getting an error The constructor AlertDialog.Builder(MainActivity.DrawerItemClickListener) is undefinedCrete
@Sameera this refers to the Context. In a clickListener, use view.getContext() or yourActivityName.thisThwack
very clean and easy to understand. thanks for this... But I have concern to something, the alert box displays No / Yes button. Is there any way to change their place? i want to display Yes / No in the alert box... But all in all, it was perfect! thanks :)Spew
@davidglorioso The order of yes/no or no/yes depends on the version of Android, and you can't control it. I don't remember when it changed, but I think it was in 4.x or 5. Saying that, you shouldn't change it anyway. All apps which use standard alert dialogs will use the same no/yes button order, and it would be confusing for users if yours were different. If you really want it to be different, you'll have to manually set your positive/negative buttons dependent on the Android version.Thwack
@SteveHaley Short & sharp! Still works out-of-the-box seven years on. Thank you.Consecutive
If you want to use the "yes" "no" literals of the user's language you can use this .setPositiveButton(android.R.string.yes, dialogClickListener) .setNegativeButton(android.R.string.no, dialogClickListener)Progress
In what scenario would I have other yes/no boxes that should do exactly the same thing?? Unless I'm mistaken I need to have a full set of the above code for every simple yes/no box use case right? If so I wouldn't consider this to be a valid answer for the question.Ploughshare
All this would be helpful EXCEPT Google in their infinite wisdom put the following in to make none of this work: <string name="yes">OK</string> <!-- Preference framework strings. --> <string name="no">Cancel</string>Spleeny
@SteveHaley how can I get a custom argument in onClick?Anni
S
186

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();
Situla answered 31/8, 2012 at 10:29 Comment(6)
Personally, I like that code snippet more than the accepted answerCultism
@Situla why do both have dismiss() ?Alkane
The constructor AlertDialog.Builder(MainActivity.DrawerItemClickListener) is undefinedCrete
@likejiujitsu thats becuse you want to clean the dialog from memory in any case after you do your work.Antedate
@Situla how can I get a custom argument in onClick?Anni
Worked like a charm in KotlinIila
I
35

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)

Iconoduly answered 19/3, 2010 at 17:16 Comment(3)
Thanks, the fact that Android dialogs are asynchronous makes everything clear (and reasonable) now. Seems I need to "think out of .Net" when developing apps for Android :)Therianthropic
FYI: what you call "asynchronous dialog" is called "modeless dialog" in the GUI terminology, whereas "synchronous dialog" is called "modal dialog". Android does not feature modal dialogs (except in very exceptional cases).Boyhood
Android doesn't allow system modal dialogs for a very good reason: is not allowed interfere with another apps on device.Scrotum
C
14

This is working for me:

AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

    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();
Crete answered 24/12, 2014 at 7:7 Comment(0)
K
10

Asking a Person whether he wants to call or not Dialog..

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class Firstclass extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.first);

        ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig);

        imageViewCall.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v){
                try{
                    showDialog("0728570527");
                } catch (Exception e){
                    e.printStackTrace();
                }                   
            }    
        });    
    }

    public void showDialog(final String phone) throws Exception {
        AlertDialog.Builder builder = new AlertDialog.Builder(Firstclass.this);

        builder.setMessage("Ring: " + phone);       

        builder.setPositiveButton("Ring", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){

                Intent callIntent = new Intent(Intent.ACTION_DIAL);// (Intent.ACTION_CALL);                 
                callIntent.setData(Uri.parse("tel:" + phone));
                startActivity(callIntent);

                dialog.dismiss();
            }
        });

        builder.setNegativeButton("Abort", new DialogInterface.OnClickListener(){   
            @Override
            public void onClick(DialogInterface dialog, int which){
                dialog.dismiss();
            }
        });         
        builder.show();
    }    
}
Knoll answered 22/4, 2014 at 6:40 Comment(0)
H
8

Kotlin implementation.

You can create a simple function like this:

fun dialogYesOrNo(
        activity: Activity,
        title: String,
        message: String,
        listener: DialogInterface.OnClickListener
    ) {
        val builder = AlertDialog.Builder(activity)
        builder.setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id ->
            dialog.dismiss()
            listener.onClick(dialog, id)
        })
        builder.setNegativeButton("No", null)
        val alert = builder.create()
        alert.setTitle(title)
        alert.setMessage(message)
        alert.show()
    }

and call it like this:

dialogYesOrNo(
  this,
  "Question",
  "Would you like to eat?",
  DialogInterface.OnClickListener { dialog, id ->
    // do whatever you need to do when user presses "Yes"
  }
})
Hydraulics answered 9/4, 2020 at 2:56 Comment(1)
Everything is fine until user leave the app with the pop up still open, if system kill the app in background, will get a WindowLeaked exceptionEvangelista
I
7

Show dialog anonymously as chain of commands & without defining another object:

 new AlertDialog.Builder(this).setTitle("Confirm Delete?")
                        .setMessage("Are you sure?")
                        .setPositiveButton("YES",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {

                                       // Perform Action & Dismiss dialog                                 
                                        dialog.dismiss();
                                    }
                                })
                        .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // Do nothing
                                dialog.dismiss();
                            }
                        })
                        .create()
                        .show();
Ignominy answered 26/12, 2017 at 11:40 Comment(0)
F
6

All the answers here boil down to lengthy and not reader-friendly code: just what the person asking was trying to avoid. To me, was the easiest approach is to employ lambdas here:

new AlertDialog.Builder(this)
        .setTitle("Are you sure?")
        .setMessage("If you go back you will loose any changes.")
        .setPositiveButton("Yes", (dialog, which) -> {
            doSomething();
            dialog.dismiss();
        })
        .setNegativeButton("No", (dialog, which) -> dialog.dismiss())
        .show();

Lambdas in Android require the retrolambda plugin (https://github.com/evant/gradle-retrolambda), but it's hugely helpful in writing cleaner code anyways.

Fideicommissum answered 26/4, 2017 at 11:48 Comment(1)
It worked great, but why don't we need to define the data types for "dialog" and "which"?Elery
A
6

In Kotlin:

AlertDialog.Builder(this)
    .setTitle(R.string.question_title)
    .setMessage(R.string.question_message)
    .setPositiveButton(android.R.string.yes) { _, _ -> yesClicked() }
    .setNegativeButton(android.R.string.no) { _, _ -> noClicked() }
    .show()
Arenicolous answered 23/11, 2017 at 10:36 Comment(1)
'android.R.string.yes: Int' is deprecated. Deprecated in JavaGemstone
T
5

Thanks nikki your answer has helped me improve an existing simply by adding my desired action as follows

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Do this action");
builder.setMessage("do you want confirm this action?");

builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {
        // Do do my action here

        dialog.dismiss();
    }

});

builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // I do not need any action here you might
        dialog.dismiss();
    }
});

AlertDialog alert = builder.create();
alert.show();
Talia answered 11/11, 2012 at 5:38 Comment(3)
I got the impression that the OP didn't want to use AlertDialog.Builder. OP wats to know if there is a shortcut utility method,Brandon
I have written the same code but NO appears first and then YES basically it is a NO / YES dialog box but I need a YES / NO dialog box How do i do itCiel
As for the YES/NO vs NO/YES see this answer: https://mcmap.net/q/87939/-android-alertdialog-move-positivebutton-to-the-right-and-negativebutton-on-the-left you can manipulate it as discribed in this answer: https://mcmap.net/q/87939/-android-alertdialog-move-positivebutton-to-the-right-and-negativebutton-on-the-leftTalia
S
5

Steves answer is correct though outdated with fragments. Here is an example with FragmentDialog.

The class:

public class SomeDialog extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
            .setTitle("Title")
            .setMessage("Sure you wanna do this!")
            .setNegativeButton(android.R.string.no, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do nothing (will close dialog)
                }
            })
            .setPositiveButton(android.R.string.yes,  new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do something
                }
            })
            .create();
    }
}

To start dialog:

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            // Create and show the dialog.
            SomeDialog newFragment = new SomeDialog ();
            newFragment.show(ft, "dialog");

You could also let the class implement onClickListener and use that instead of embedded listeners.

Sulphurize answered 23/4, 2013 at 16:52 Comment(13)
@likejiujitsu above is sufficient.Sulphurize
Create a FragmentDialog class just to do a no/yes box is a bit of overdesign... :) A default AlertDialog is fair enough, yet.Scrotum
@Scrotum yes but I believe it is obsolete.Sulphurize
Not really. FragmentDialog was added as a useful thing to allow you to reuse a fragment on a dialog. Fragments is all about UI reuse. As you don't need use fragments just because is a new thing (fragments not come to replace activities), you don't need to use FragmentDialog on cases where is no gain to do. Simple Yes/No alerts, for instance.Scrotum
To better info (from Android Developer Guide, on developer.android.com/guide/topics/ui/dialogs.html): "The DialogFragment class also allows you to reuse the dialog's UI as an embeddable component in a larger UI, just like a traditional Fragment (such as when you want the dialog UI to appear differently on large and small screens)."Scrotum
My recommendation is: if you need reuse not just a layout, but background and lifecycle code, use a Fragment dialog. With the fragment you have the related activity lifecycle control and can react to events like create (as the UI is re-created when user rotate his device), pause, resume, etc. On a nutshell, a dialog with some elaborated UI. If you don't need this and your dialog is pretty simple, regular dialogs works fine.Scrotum
How do I react to the results?Jenninejennings
@Jenninejennings Do something inside onClick.Sulphurize
@Sulphurize Like...set the value of some global variable?Jenninejennings
@Jenninejennings You have 2 listeners. 1 for positive = yes, 1 for negative = no. So basically do whatever you want to do inside each.Sulphurize
@Sulphurize But then my whole code goes into the onClick listener? Isn't that stupid? How would my code then react to other things in the app?Jenninejennings
@Jenninejennings Basically you just make a method somewhere and call said method from within the onClick listener. I'd recommend taking some basic coding classes etc. This is very basic.Sulphurize
Maybe. Though I am not coding professionally. I have some books on C++, Java is kinda new for me. But even with C++ I am a novice of 20+ years experience, just using it to solve basic tasks where it is handy. So, a course will quickly be forgotten :)Jenninejennings
S
2

1.Create AlertDialog set message,title and Positive,Negative Button:

final AlertDialog alertDialog = new AlertDialog.Builder(this)
                        .setCancelable(false)
                        .setTitle("Confirmation")
                        .setMessage("Do you want to remove this Picture?")
                        .setPositiveButton("Yes",null)
                        .setNegativeButton("No",null)
                        .create();

2.Now find both buttons on DialogInterface Click then setOnClickListener():

alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                Button yesButton = (alertDialog).getButton(android.app.AlertDialog.BUTTON_POSITIVE);
                Button noButton = (alertDialog).getButton(android.app.AlertDialog.BUTTON_NEGATIVE);
                yesButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //Now Background Class To Update Operator State
                        alertDialog.dismiss();
                        Toast.makeText(GroundEditActivity.this, "Click on Yes", Toast.LENGTH_SHORT).show();
                        //Do Something here 
                    }
                });

                noButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                        Toast.makeText(GroundEditActivity.this, "Click on No", Toast.LENGTH_SHORT).show();
                        //Do Some Thing Here 
                    }
                });
            }
        });

3.To Show Alertdialog:

alertDialog.show();

Note: Don't forget Final Keyword with AlertDialog.

Subheading answered 1/2, 2018 at 6:39 Comment(0)
H
1

Thanks. I use the API Level 2 (Android 1.1) and instead of BUTTON_POSITIVE and BUTTON_NEGATIVE i have to use BUTTON1 and BUTTON2.

Hydraulics answered 27/1, 2011 at 6:18 Comment(0)
A
1

For Kotlin in Android::

    override fun onBackPressed() {
        confirmToCancel()
    }

    private fun confirmToCancel() {
        AlertDialog.Builder(this)
            .setTitle("Title")
            .setMessage("Do you want to cancel?")
            .setCancelable(false)
            .setPositiveButton("Yes") {
                dialog: DialogInterface, _: Int ->
                dialog.dismiss()
                // for sending data to previous activity use
                // setResult(response code, data)
                finish()
            }
            .setNegativeButton("No") {
                dialog: DialogInterface, _: Int ->
                dialog.dismiss()
            }
            .show()
    } 
Ame answered 27/1, 2020 at 17:6 Comment(0)
G
0
AlertDialog.Builder altBx = new AlertDialog.Builder(this);
    altBx.setTitle("My dialog box");
    altBx.setMessage("Welcome, Please Enter your name");
    altBx.setIcon(R.drawable.logo);

    altBx.setPositiveButton("Ok", new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int which)
      {
          if(edt.getText().toString().length()!=0)
          {
              // Show any message
          }
          else 
          {

          }
      }
    });
    altBx.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int which)
      {
          //show any message
      }

    });
  altBx.show();  
Greeley answered 28/9, 2013 at 8:21 Comment(0)
C
0

you can implement a generic solution for decisions and use in another case not just for yes/no and custom the alert with animations or layout:

Something like this; first create your class for transfer datas:

public class AlertDecision {

    private String question = "";
    private String strNegative = "";
    private String strPositive = "";

    public AlertDecision question(@NonNull String question) {
        this.question = question;
        return this;
    }

    public AlertDecision ansPositive(@NonNull String strPositive) {
        this.strPositive = strPositive;
        return this;
    }

    public AlertDecision ansNegative(@NonNull String strNegative) {
        this.strNegative = strNegative;
        return this;
    }

    public String getQuestion() {
        return question;
    }

    public String getAnswerNegative() {
        return strNegative;
    }

    public String getAnswerPositive() {
        return strPositive;
    }
}

after a interface for return the result

public interface OnAlertDecisionClickListener {

    /**
     * Interface definition for a callback to be invoked when a view is clicked.
     *
     * @param dialog the dialog that was clicked
     * @param object The object in the position of the view
     */
    void onPositiveDecisionClick(DialogInterface dialog, Object object);
    void onNegativeDecisionClick(DialogInterface dialog, Object object);
}

Now you can create an utils for access easily (in this class you can implement different animation or custom layout for the alert):

public class AlertViewUtils {

    public static void showAlertDecision(Context context,
                                         @NonNull AlertDecision decision,
                                         final OnAlertDecisionClickListener listener,
                                         final Object object) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(decision.getQuestion());
        builder.setPositiveButton(decision.getAnswerPositive(),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        listener.onPositiveDecisionClick(dialog, object);
                    }
                });

        builder.setNegativeButton(decision.getAnswerNegative(),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        listener.onNegativeDecisionClick(dialog, object);
                    }
                });

        android.support.v7.app.AlertDialog dialog = builder.create();
        dialog.show();
    }
}

and the last call in activity or fragment; you can use this in you case or for other task:

public class MainActivity extends AppCompatActivity {

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
        initResources();
    }

    public void initResources() {
        Button doSomething = (Button) findViewById(R.id.btn);
        doSomething.setOnClickListener(getDecisionListener());
    }

    private View.OnClickListener getDecisionListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDecision decision = new AlertDecision()
                        .question("question ...")
                        .ansNegative("negative action...")
                        .ansPositive("positive action... ");
                AlertViewUtils.showAlertDecision(MainActivity.this,
                        decision, getOnDecisionListener(), v);
            }
        };
    }

    private OnAlertDecisionClickListener getOnDecisionListener() {
        return new OnAlertDecisionClickListener() {
            @Override
            public void onPositiveDecisionClick(DialogInterface dialog, Object object) {

                //do something like create, show views, etc...
            }

            @Override
            public void onNegativeDecisionClick(DialogInterface dialog, Object object) {
                //do something like delete, close session, etc ...
            }
        };
    }
} 
Columbous answered 28/2, 2017 at 19:38 Comment(0)
J
0

You can do it so easy in Kotlin:

 alert("Testing alerts") {
    title = "Alert"
    yesButton { toast("Yess!!!") }
    noButton { }
}.show()
Joggle answered 17/5, 2018 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.