I need to dismiss DialogFragment in onStop() of an FragmentActivity if it is showing, this is what I did
if(mAlertDlg != null && mAlertDlg.getDialog() != null)
mAlertDlg.dismiss();
But I usually got IllegalStateException. So please tell me why that code is wrong and what is the correct way to dismiss DialogFragment in onStop()? Thank you.
If you want to dismiss a DialogFragment
in onStop()
, you probably don't want to use a DialogFragment
but a classic Dialog
instead.
The reason why DialogFragment
exists is to allow a dialog to be restored automatically when the Activity is re-created. If you dismiss it in onStop()
, it will never be restored.
Also, if you use dismissAllowingStateLoss()
, the dismiss transaction may not be recorded properly in onSaveInstanceState()
(as the name says, a state loss may occur), and this will result in the dialog being restored when the activity is re-created, and obviously that's not what you want.
You should use dialogFragment.dismissAllowingStateLoss()
. As the documentation say for commitAllowingStateLoss()
:
"Like commit() but allows the commit to be executed after an activity's state is saved. This is dangerous because the commit can be lost if the activity needs to later be restored from its state, so this should only be used for cases where it is okay for the UI state to change unexpectedly on the user."
So for dismissAllowingStateLoss()
is the same approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With