How to use Dialog Fragment? (showDialog deprecated) Android

You can show your DialogFragment like this:

void showDialog() {
    DialogFragment newFragment = MyAlertDialogFragment.newInstance(
            R.string.alert_dialog_two_buttons_title);
    newFragment.show(getFragmentManager(), "dialog");
}

In you fragment dialog you should override onCreateDialog and return you instance of simple Dialog, for example AlertDialog.

public static class MyAlertDialogFragment extends DialogFragment {

public static MyAlertDialogFragment newInstance(int title) {
    MyAlertDialogFragment frag = new MyAlertDialogFragment();
    Bundle args = new Bundle();
    args.putInt("title", title);
    frag.setArguments(args);
    return frag;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    int title = getArguments().getInt("title");

    AlertDialog.Builder builder = new Builder(this);
    return builder
                .setMessage("Are you sure you want to reset the count?")
                .setNegativeButton("No", new DialogInterface.OnClickListener() {    

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        Toast.makeText(MainActivity.this, "Did not reset!", 5).show();

                    }
                })

                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {


                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        Toast.makeText(MainActivity.this, "Did Reset!", 5).show();

                    }
                })
                .create();
}
}

Leave a Comment