How does one programatically dismiss a DialogFragment? I am currently creating dialogs by:
void showDialogWithId(int id){ FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); if (id == SEARCHING_DIALOG){ // Create and show the dialog. DialogFragment newFragment = MyDialogFragment.newInstance(SEARCHING_DIALOG,"TEST"); newFragment.show(ft, "dialog"); } if (id == CONNECTING_DIALOG){ // Create and show the dialog. DialogFragment newFragment = MyDialogFragment.newInstance(CONNECTING_DIALOG,"TEST"); newFragment.show(ft, "dialog"); } if (id == CONNECTIVITY_DIALOG){ // Create and show the dialog. DialogFragment newFragment = MyDialogFragment.newInstance(CONNECTIVITY_DIALOG); newFragment.show(ft, "dialog"); } }
And I expect to dismiss them by:
public void dismissDialog(){ getFragmentManager().popBackStack(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); }
However, the dialogs are not being dismissed...
tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment. 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.
This class was deprecated in API level 28. Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle.
This is gonna be disappointing to you "great" finding but just call progressDialog. showDialog() twice back-to-back and you will get two dialogs. Because show is asynchronous and your findFragmentByTag(TAG) == null check will be true until dialog is actually added by system.
Dialog: A dialog is a small window that prompts the user to make a decision or enter additional information. DialogFragment: A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.
Try using
getDialog().dismiss();
Inside the DialogFragments. So for example you could find the DialogFragment by its tag, like you do so, and then call some method on it that calls this code. I'm usually don't initiate a dismiss of a DialogFragment from the Activity, my dialog buttons do that for me. But I think that this should also work. I'm not sure how this would affect the fragment backstack tho.
To aggregate the previous response and the associated comments, to remove the Dialog you have to do:
public void dismissDialog(){ Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog"); if (prev != null) { DialogFragment df = (DialogFragment) prev; df.dismiss(); } }
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