ProgressDialog (fragment) that works through the orientation switch

Can anyone see if I am doing the following correctly. I have a fragment with a progressive dialog, and I need it to work through the orientation switch. I am currently doing it like this:

// 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 just return mProgressDialog if it already exists (I get an exception: "requestFeature () must be called before adding content"). Of course, one way to use fragments is to reuse resources in these cases - why do I need to create a new dialog box instead of using the one that already exists?

+6
source share
1 answer

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

If you do not re-create the dialog box, u will end up with a memory leak.

+2
source

All Articles