Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ProgressDialog (Fragment) that works across an orientation switch

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?

like image 949
Lieuwe Avatar asked Jan 05 '13 20:01

Lieuwe


1 Answers

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.

like image 180
Marco RS Avatar answered Nov 15 '22 10:11

Marco RS