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...
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Solo
  • 4,116
  • 2
  • 17
  • 9
  • http://stackoverflow.com/questions/2028697/dialogs-alertdialogs-how-to-block-execution-while-dialog-is-up-net-style?lq=1 – Mertuarez Dec 05 '12 at 21:09
  • 3
    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? – Ravikumar11 Apr 21 '15 at 06:31
  • 2
    Yes.... we .NET developers really do have a hard time with android....I wonder if Xamarin is a great tool? – Daniel Möller Jul 14 '17 at 02:43

17 Answers17

793

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

Steve Haley
  • 55,374
  • 17
  • 77
  • 85
  • 3
    new AlertDialog.Builder(this); Compile time error: 'The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined' – Eric Leschinski Apr 04 '12 at 23:54
  • if i want to dismiss that dialog box, what should write under case DialogInterface.BUTTON_NEGATIVE case. – Vijay Bagul Apr 05 '12 at 10:29
  • @VijayBagul `dialog.dismiss();` – Tushar May 15 '12 at 01:09
  • 3
    Simple and useful, btw, dialog will dismiss itself after user click "YES" or "NO" button. There is nothing you need to do. – RRTW Mar 08 '13 at 07:31
  • 11
    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. – Radu Mar 21 '13 at 13:47
  • 4
    @EricLeschinski probably "this" isn't a context, try this one: `AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext());` – cldrr May 16 '13 at 07:43
  • im getting an error `The constructor AlertDialog.Builder(MainActivity.DrawerItemClickListener) is undefined` – hash Dec 24 '14 at 06:51
  • @Sameera `this` refers to the Context. In a clickListener, use `view.getContext()` or `yourActivityName.this` – Steve Haley Jan 05 '15 at 18:00
  • 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 :) – david glorioso May 28 '16 at 10:10
  • 1
    @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. – Steve Haley Jun 01 '16 at 13:57
  • @SteveHaley Short & sharp! Still works out-of-the-box seven years on. Thank you. – iSofia Sep 21 '17 at 18:53
  • 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)` – Thanasis Kapelonis Feb 16 '19 at 14:50
  • 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. – iforce2d May 04 '19 at 10:12
  • All this would be helpful EXCEPT Google in their infinite wisdom put the following in to make none of this work: OK Cancel – Mitch Feb 27 '20 at 05:36
  • @SteveHaley how can I get a custom argument in onClick? – Rohit Nishad Dec 05 '20 at 07:29
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();
Gene Bo
  • 11,284
  • 8
  • 90
  • 137
nikki
  • 3,248
  • 3
  • 24
  • 29
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)

Community
  • 1
  • 1
Erich Douglass
  • 51,744
  • 11
  • 75
  • 60
  • 8
    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 :) – Solo Mar 21 '10 at 06:58
  • 1
    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). – Alex Dec 22 '12 at 20:18
  • Android doesn't allow system modal dialogs for a very good reason: is not allowed interfere with another apps on device. – Renascienza Dec 26 '14 at 11:42
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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hash
  • 5,336
  • 7
  • 36
  • 59
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();
    }    
}
Elio Lako
  • 1,333
  • 2
  • 16
  • 26
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
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"
  }
})
Christian
  • 7,062
  • 9
  • 53
  • 79
  • 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 exception – BabyishTank Oct 28 '21 at 01:11
7

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.

javaxian
  • 1,815
  • 1
  • 21
  • 26
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();
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
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()
Cristan
  • 12,083
  • 7
  • 65
  • 69
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();
Billy
  • 607
  • 2
  • 8
  • 20
CrandellWS
  • 2,708
  • 5
  • 49
  • 111
  • 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, – walrii Nov 11 '12 at 06:03
  • 1
    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 it – Sagar Devanga Aug 19 '14 at 19:19
  • As for the YES/NO vs NO/YES see this answer: http://stackoverflow.com/a/13644589/1815624 you can manipulate it as discribed in this answer: http://stackoverflow.com/a/13644536/1815624 – CrandellWS Aug 23 '14 at 16:51
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.

Warpzit
  • 27,966
  • 19
  • 103
  • 155
  • @likejiujitsu above is sufficient. – Warpzit Mar 16 '14 at 06:03
  • Create a FragmentDialog class just to do a no/yes box is a bit of overdesign... :) A default AlertDialog is fair enough, yet. – Renascienza Dec 26 '14 at 11:46
  • @Renascienza yes but I believe it is obsolete. – Warpzit Dec 26 '14 at 12:37
  • 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. – Renascienza Dec 26 '14 at 16:33
  • To better info (from Android Developer Guide, on http://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)." – Renascienza Dec 26 '14 at 16:43
  • 2
    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. – Renascienza Dec 26 '14 at 17:20
  • How do I react to the results? – TJJ Apr 30 '21 at 19:32
  • @TJJ Do something inside onClick. – Warpzit May 19 '21 at 11:04
  • @Warpzit Like...set the value of some global variable? – TJJ May 20 '21 at 14:51
  • @TJJ You have 2 listeners. 1 for positive = yes, 1 for negative = no. So basically do whatever you want to do inside each. – Warpzit May 21 '21 at 07:01
  • @Warpzit 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? – TJJ May 21 '21 at 11:16
  • 1
    @TJJ 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. – Warpzit Jun 01 '21 at 10:01
  • 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 :) – TJJ Jun 04 '21 at 13:22
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.

Wajid khan
  • 842
  • 9
  • 18
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.

user253751
  • 57,427
  • 7
  • 48
  • 90
Christian
  • 11
  • 1
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()
    } 
Partha Paul
  • 189
  • 4
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();  
Singhak
  • 8,508
  • 2
  • 31
  • 34
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 ...
            }
        };
    }
} 
Alex Zaraos
  • 6,443
  • 2
  • 26
  • 21
0

You can do it so easy in Kotlin:

 alert("Testing alerts") {
    title = "Alert"
    yesButton { toast("Yess!!!") }
    noButton { }
}.show()
Serg Burlaka
  • 2,351
  • 24
  • 35