Search code examples
androidprogressdialogandroid-dialogfragment

Custom Dialog using DialogFragment


I just recently am trying to convert an app that uses a ProgressDialog that extends DialogFragment, not Dialog.

How can you

  1. Create a Custom Dialog Class extending DialogFragment
  2. Then load the dialog by calling this class from Activity

Can I see a super basic example? What methods to override? And what about the constructor?

Right now this is what I am doing (the old way):

private MyProgressDialog progressDialog = new MyProgressDialog(
                    getActivity());
progressdialog.show();

Solution

  • So you want a progress dialog fragment?

    It's actually really simple. DialogFragments are just Fragments that wrap around a dialog, so you just need to create your dialog as usual in the onCreateDialog method of the DialogFragment.

    e.g.

    class ProgressDialogFragment extends DialogFragment{
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            ProgressDialog dialog = new ProgressDialog(getActivity());
            dialog.setMessage("Loading");
            return dialog;
        }
    }
    

    And to show the DialogFragment:

    mButton = (Button)getView().findViewById(R.id.button1);
    mButton.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {
            new ProgressDialogFragment().show(getFragmentManager(), "MyProgressDialog");
        }
    });