ProgressDialog (Fragment) that works across an orientation switch
Asked Answered
S

1

6

Can anyone have a look if I am doing the following correctly. I have a fragment that has a progressdialog and I need it to work across an orientation switch. I currently do this like so:

// I am using the compat libraries
import android.support.v4.app.DialogFragment;

public class ProgressDialogFragment extends DialogFragment {

    private ProgressDialog mProgressDialog = null;
    private int            mMax            = 100;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, 0);
        setRetainInstance(true);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setTitle("Title");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setProgress(0);
        mProgressDialog.setMax(mMax);
        mProgressDialog.setCanceledOnTouchOutside(false);

        return mProgressDialog;
    }

    // there seems to be a bug in the compat library - if I don't do the following - the dialog is not show after an orientation switch
    @Override
    public void onDestroyView() {
        if (getDialog() != null && getRetainInstance())
            getDialog().setDismissMessage(null);
        super.onDestroyView();
    }

    public void setMax(int arg1) {
        mProgressDialog.setMax(arg1);
        mMax = arg1;
    }

    public void setProgress(int arg1) {
        mProgressDialog.setProgress(arg1);
    }
}

In my Activity I create this ProgressDialogFragment and I call show() when I need the dialog to show. I am trying to understand why in the onCreateDialog method I cannot simply return the mProgressDialog if it already exists (I get an exception saying "requestFeature() must be called before adding content"). Surely one of the uses of fragments is to re-use resources in these cases - why do I need to create a new dialog instead of using the one that is already there?

Sputum answered 5/1, 2013 at 20:34 Comment(0)
A
2

You cannot simply pass the old dialog in the onCreateDialog method because it has a reference to the old context ie the activity that is being destroyed.

If you do not recreate the dialog then u will end up with a memory leak.

Aegisthus answered 7/1, 2013 at 20:19 Comment(4)
The onCreate method isn't being called on an orientation switch - the fragment isn't destroyed & then recreated.Sputum
Sorry I meant the onCreateDialog method which will be called again.Aegisthus
Are you trying to save the progress between orientation changes?Aegisthus
No - the Thread that updates the dialog sends its progress fast enough so you don't notice it. I do save the "max" setting as you see.Sputum

© 2022 - 2024 — McMap. All rights reserved.