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

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

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 such as adapters and other heavier objects and I need this to be kept upon rotation, if possible without having to make every reference Parcelable or Serializable in order for me to use onSaveInstanceState to save and restore them when the original activity is re-created.

I've noticed there's a method called setRetainInstance(boolean) on the DialogFragment which allows you to keep the dialog fragment instance when the activity is re-created. However, when I rotate the device now, the dialog is not showing anymore. I know I can get it from the activity's FragmentManager, but I cannot find a way to make it visible again. Any suggestions on this?

Thanks, Mihai

回答1:

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") 


回答2:

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.


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