Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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("Are You Sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)

{

                //Do something...

}

Thanks for your input.

share|improve this question
    

9 Answers 9

up vote 343 down vote accepted

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

share|improve this answer
1  
Thanks Steve... :) –  Chetan Bhalara Oct 20 '11 at 8:31
3  
new AlertDialog.Builder(this); Compile time error: 'The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined' –  Eric Leschinski Apr 4 '12 at 23:54
2  
Simple and useful, btw, dialog will dismiss itself after user click "YES" or "NO" button. There is nothing you need to do. –  RRTW Mar 8 '13 at 7:31
3  
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
3  
@EricLeschinski probably "this" isn't a context, try this one: AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext()); –  ledererc May 16 '13 at 7:43

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();
share|improve this answer
1  
Personally, I like that code snippet more than the accepted answer –  John Dec 30 '13 at 10:22
    
@nikki why do both have dismiss() ? –  likejiujitsu Mar 15 '14 at 19:00
    
This worked better for me then the answer also –  Tom Apr 9 '14 at 21:11
    
The constructor AlertDialog.Builder(MainActivity.DrawerItemClickListener) is undefined –  Sameera Dec 24 '14 at 6:49

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): http://stackoverflow.com/questions/2028697/dialogs-alertdialogs-how-to-block-execution-while-dialog-is-up-net-style

share|improve this answer
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 6:58
    
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

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.

share|improve this answer
    
no endTransaction() necessary? –  likejiujitsu Mar 15 '14 at 19:24
    
@likejiujitsu above is sufficient. –  Warpzit Mar 16 '14 at 6: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
1  
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

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();
share|improve this answer
    
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 6: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: stackoverflow.com/a/13644589/1815624 you can manipulate it as discribed in this answer: stackoverflow.com/a/13644536/1815624 –  CrandellWS Aug 23 '14 at 16:51

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();
    }

}
share|improve this answer
    
Thank your.this is work for me –  Sameera Dec 24 '14 at 7:09

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.

share|improve this answer
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();  
share|improve this answer

This is work 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();
share|improve this answer

protected by Community Feb 27 '14 at 18:58

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.