Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DialogFragment not retained on orientation change

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?

like image 918
patman Avatar asked Dec 19 '25 19:12

patman


1 Answers

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();
}
like image 173
android developer Avatar answered Dec 21 '25 13:12

android developer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!