0

I am using a dialog fragment CDialogFragment in my app. I need to dismiss my DialogFragment on Activity recreation. To handle I used dismiss() method as -

 @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogSlideAnim2);
    setRetainInstance(true);
    if(savedInstanceState!=null){
      dismiss();
    }
  }

Its is working fine, On Activity recreation my dialog fragment dismissed.

Problem is that after calling dismiss in onCreate(), onActivityCreated() is being called.

To stop onActivityCreated(), I used code in onCreate() as -

    if(savedInstanceState!=null){
     dismiss(); 
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
    }

But not able to stop onActivityCreated()

I also used onDetached() but no solution

Please give a solution

Sanjay Kumar
  • 1,135
  • 14
  • 27
  • "I need to dismiss my DialogFragment on Activity recreation" -- that makes little sense. You are saying that if the user rotates the screen, or you otherwise undergo a configuration change, that you want the dialog to disappear. That is odd, but if it is truly what you want, stop using `DialogFragment`. The **complete and entire *point*** of `DialogFragment` is to retain and re-display the dialog after a configuration change. – CommonsWare May 01 '17 at 14:45

1 Answers1

1

To solve this, destroy it a lot earlier: no need to recreate it when you don't want to show it again.

  1. When you show/create your dialog, save it in a global parameter in your Activity: Dialog dialog.
  2. onStop of your activity, dismiss it so that it won't come back in your new creation: dialog.dismiss();
Frank
  • 12,010
  • 8
  • 61
  • 78
  • ava.lang.IllegalStateException: Can not perform this action after onSaveInstanceState if I dismiss() dialog in onStop() – Sanjay Kumar May 02 '17 at 06:02
  • then call it in onSaveInstanceState(Bundle) maybe, before calling the super. that method is always called if the system thinks it might restore the instance in the future. – Frank May 02 '17 at 12:14