DialogFragment with setRetainInstanceState(true) is not displayed after the device is rotated

后端 未结 2 619
误落风尘
误落风尘 2020-12-24 15:13

I have a question regarding DialogFragment. I am trying to make a dialog that keeps it\'s state after the device is rotated. This dialog has a bunch of references to things

相关标签:
2条回答
  • 2020-12-24 15:30

    There are few things you need to do :

    1. use instance factory method to initiate a DialogFragment instance like this :

      public static MyDialogFragment newInstance(MyModel model) {
          MyDialogFragment myDialogFragment = new MyDialogFragment();
          Bundle bundle = new Bundle();
          bundle.putSerializable("MODEL", model);
          myDialogFragment .setArguments(bundle);
          return myDialogFragment;
      }
      
    2. by putting setRetainInstance(true) in onCreate, all of your references declared in the fragment will be kept after the original activity is re-created

      @Override
      public void onCreate(Bundle icicle) {
          this.setCancelable(true);
          setRetainInstance(true);
          super.onCreate(icicle);
      
      }
      
    3. avoiding disappear on rotation by doing this

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

      }

    4. get your object by using

      (MyModel) getArguments().getSerializable("MODEL")
      
    0 讨论(0)
  • 2020-12-24 15:53

    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 need to manually store off the values. 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.
    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.
    0 讨论(0)
提交回复
热议问题