We add a general/normal Fragment
programatically by doing something like:
fragmentTransaction.add(containerViewId, fragmentToAdd, fragmentTag);
and we replace a Fragment
by another by doing something like:
fragmentTransaction.replace(containerViewId, newFragment, tagOfNewFragment);
But we add a DialogFragment
by
dialogFramentInstance.show(fragmentManager, fragmentTag);
The question is that how should I replace this DialogFragment
which has been added by the show()
method?
Essentially a DialogFragment displays a Dialog but inside a Fragment. Google recommends that we use DialogFragment instead of a simple Alert Dialog builder in the activity. Why so? DialogFragments have their own lifecycle methods. So the Activity is free from the responsibility of telling the Dialog what to do.
When creating a DialogFragment from within a Fragment, you must use the Fragment 's child FragmentManager to ensure that the state is properly restored after configuration changes. A non-null tag allows you to use findFragmentByTag () to retrieve the DialogFragment at a later time. // PurchaseConfirmationDialogFragment.
DialogFragment also contains methods to dismiss or set the cancellability of your DialogFragment: 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 are popped.
Instead of DialogFragment, you can extend from BottomSheetDialogFragment: When you show this fragment, you will notice that it appears from the bottom: Notice that we are using the support library version of fragments for better compatibility in our code samples. The non-support version works identically.
dialogFramentInstance.show(fragmentManager, fragmentTag);
Just adds the dialog fragment to the fragment manger using an add transaction (with no container).
In order to replace fragments you'll need a container and since you don't have one your only option is to dismiss()
the first one and show()
the new one.
private void closeYourDialogFragment() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragmentToRemove = getSupportFragmentManager().findFragmentByTag("your_dialog_fragment");
if (fragmentToRemove != null) {
ft.remove(fragmentToRemove);
}
ft.addToBackStack(null);
ft.commit(); // or ft.commitAllowingStateLoss()
}
private void replaceYourDialogFragment() {
closeYourDialogFragment();
YourDialogFragment yourDialogFragment = new YourDialogFragment();
yourDialogFragment.show(getSupportFragmentManager(), "your_dialog_fragment");
}
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