How to safely reject DialogFragment in onstop ()?

I need to remove DialogFragment in onStop () from FragmentActivity, if it shows, here is what I did

if(mAlertDlg != null && mAlertDlg.getDialog() != null) mAlertDlg.dismiss(); 

But I usually get IllegalStateException. So please tell me why this code is wrong and what is the correct way to remove DialogFragment in onStop ()? Thanks.

+6
source share
3 answers

You should use dialogFragment.dismissAllowingStateLoss() . As the documentation says for commitAllowingStateLoss() :

“Like commit (), but allows committing after the activity state is saved. This is dangerous because committing can be lost if the activity needs to be restored later from its state, so this should only be used when it’s normal for the state the user interface changes unexpectedly to the user. "

So for dismissAllowingStateLoss() the same approach is used.

+14
source

If you want to reject DialogFragment in onStop() , you most likely will not want to use DialogFragment , but the classic Dialog .

The reason DialogFragment exists is to allow the restoration of the dialog box automatically when activity is restored. If you release it in onStop() , it will never be restored.

In addition, if you use dismissAllowingStateLoss() , the reject transaction may be incorrectly written to onSaveInstanceState() (as the name says, a loss of state may occur), and this will lead to the restoration of the dialogue when the action is recreated, and obviously this is not that you want.

+4
source

Try using dismissAllowingStateLoss() instead of dismiss() .

+2
source

Source: https://habr.com/ru/post/946197/


All Articles