Android DialogFragment disappears after orientation change

我们两清 提交于 2019-11-28 04:53:57
AlexIIP

Okay, so the issue seems to be with the DialogFragment compatibility library.

The issue was described in this post.

"An obsolete DISMISS message for the fragment is retained in the message queue. It's been queued by DialogFragment.onDestroyView() when dismissing the old dialog and gets reactivated after creating the new dialog.

A quick (and possibly dirty) workaround is to override onDestroyView() and clear the dismiss listener before calling super.onDestroyView()"

Adding the following code to my DialogFragment solved the issue:

 @Override
 public void onDestroyView() {
     if (getDialog() != null && getRetainInstance()) {
         getDialog().setDismissMessage(null);
     }
     super.onDestroyView();
 }

In the interest of the poor soul (Me) who has the same issue for different reasons, I'm going to post this. The dialog fragment should be preserved automatically as long as you do the following:

  1. If you call an Activity onSaveInstanceState(), make sure you call the super function!!!!. In my case, that was the key. Also make sure you do the same thing in the Fragment.
  2. If you use setRetainInstance, you will need to manually store off the values and re-apply them. Otherwise, you should be able to not worry about it, in most cases. If you're doing something a bit more complicated, you might need to setRetainInstance(true), but otherwise ignore it. In my case, I needed to use it to store a random seed for one of my classes, but otherwise I was okay.
  3. Some people have complained about a bug in the support library, where a dismiss message is sent when it shouldn't be. The latest support library seems to have fixed that, so you shouldn't need to worry about that.

You shouldn't need to do anything fancy like manually store off the fragment, it should be done automatically if you follow these steps. Overall, this seems to do the trick for anyone with a more modern support library.

In my case I had a DialogFragment showing another DialogFragment using

listDialogFragment.show(getChildFragmentManager(), "TAG");

Changing it to

listDialogFragment.show(getActivity().getSupportFragmentManager(), "TAG");

fixed the issue

In addition to setting setRetainInstance(true); just place the following code in your DialogFragment. It is a tested solution.

private boolean isDismissible = false;

@Override
public void dismiss() {

    try {

        isDismissible = true;
        super.dismiss();

        Log.d(getClass().getSimpleName(), "Dialog dismissed!");

    } catch (IllegalStateException ilse) {
    }
}

@Override
public void onDismiss(DialogInterface dialog) {

    // So that dialog should not dismiss on orientation change
    if (isDismissible) {

        // So that dialog can be dismissed
        super.onDismiss(dialog);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!