How to correctly dismiss a DialogFragment?
I think a better way to close a DialogFragment
is this:
Fragment prev = getSupportFragmentManager().findFragmentByTag("fragment_dialog");
if (prev != null) {
DialogFragment df = (DialogFragment) prev;
df.dismiss();
}
This way you dont have to hold a reference to the DialogFragment
and can close it from everywhere.
tl;dr: The correct way to close a DialogFragment
is to use dismiss()
directly on the DialogFragment.
Details: The documentation of DialogFragment states
Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.
Thus, you should not use getDialog().dismiss()
, since that would invoke dismiss()
on the dialog. Instead, you should use the dismiss()
method of the DialogFragment itself:
public void dismiss()
Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.
As you can see, this takes care not only of closing the dialog but also of handling the fragment transactions involved in the process.
You only need to use onStop
if you explicitly created any resources that require manual cleanup (closing files, closing cursors, etc.). Even then, I would override onStop
of the DialogFragment rather than onStop
of the underlying Dialog.