I'm simply trying to retain a Dialog on orientation in Android, which i thought would be simple. But it doesn't work as i thought it would. I have a simple member class of my Activity
called StartMonitoringDialogFragment
which extends DialogFragment
. In my activty i show it like:
StartMonitoringDialogFragment dialog = new StartMonitoringDialogFragment();
dialog.show(getFragmentManager(), getClass().getName() + "StartDialog");
However the dialog doesn't appear on orientation change. I have noticed that the fragments onCreateView correctly gets called after the orientation change and is creating and returning its view correctly (instance variables of fragment still set), however nothing is displayed. Isn't it supposed to be displayed? do i need to track it manually?
Edit I tried to solve this by adding
Fragment dialog;
if(savedInstanceState != null && (dialog = getFragmentManager().findFragmentByTag(getClass().getName() + "StartDialog")) != null) {
((DialogFragment)dialog).show(getFragmentManager(), getClass().getName() + "StartDialog");
}
to my Activities onCreate(Bundle savedInstanceState)
method and it initially seemed to worked, however i'm now constantly facing an exception java.lang.IllegalStateException: Fragment already added
. Any ideas what to do?
This is a known issue, which for some reason occurs even without the support library.
In any case, one workaround that I've found to work, is adding this to each DialogFragment you have (or the base one that all will extend, of course) :
@Override
public void onDestroyView() {
//workaround for this issue: https://code.google.com/p/android/issues/detail?id=17423 (unable to retain instance after configuration change)
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}