Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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... } 
like image 911
Solo Avatar asked Mar 19 '10 15:03

Solo


People also ask

What is a dialog window in Android?

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed. Dialog Design.


2 Answers

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

like image 159
Steve Haley Avatar answered Sep 29 '22 19:09

Steve Haley


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(); 
like image 39
nikki Avatar answered Sep 29 '22 20:09

nikki