Muz Muz - 10 months ago 89
Android Question

Simplest yes/no dialog fragment

I'd like to make a

dialog fragment
that asks "Are you sure?" with a "yes/no" reply.

I've looked at the documentation and it's really verbose, going all over the place, explaining how to make advanced dialog boxes, but no intact code on making a simple 'hello world' kind of dialog box. Most tutorials utilize the deprecated dialog box system. The official blog seems to be unnecessarily complicated and difficult to understand.

So, what's the simplest way to create and display a really basic Alert Dialog? Bonus points if it's using the support library.

Answer Source

A DialogFragment is really just a fragment that wraps a dialog. You can put any kind of dialog in there by creating and returning the dialog in the onCreateDialog() method of the DialogFragment.

Heres an example DialogFragment:

class MyDialogFragment extends DialogFragment{
    Context mContext;
    public MyDialogFragment() {
        mContext = getActivity();
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
        alertDialogBuilder.setMessage("Are you sure?");
        //null should be your on click listener
        alertDialogBuilder.setPositiveButton("OK", null);
        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

        return alertDialogBuilder.create();

To create the dialog call:

new MyDialogFragment().show(getFragmentManager(), "MyDialog");

And to dismiss the dialog from somewhere:


All of that code will work perfectly with the support library, by just changing the imports to use the support library classes.