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
There are few things you need to do :
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;
}
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);
}
avoiding disappear on rotation by doing this
@Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
get your object by using
(MyModel) getArguments().getSerializable("MODEL")
The dialog fragment should be preserved automatically as long as you do the following:
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.