I'm trying avoid adding the same fragment to backStack with this method:
public static void replaceFragment(FragmentManager fragmentManager, Fragment fragment, Boolean addToBackStack) {
String backStateName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);
if (addToBackStack && !fragmentPopped && fragmentManager.findFragmentByTag(backStateName) == null) {
fragmentManager
.beginTransaction()
// .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(backStateName) // was 'backStateName'
.commit();
} else {
if (!addToBackStack)
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager
.beginTransaction()
// .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.disallowAddToBackStack()
.commit();
}
}
Navigation Drawer contains: ImageView with profilePhoto
which opens ProfileMainFragment
and few categories which opens MainFragmentCategory
. Boolean addToBackStack
is false
when fragment is choosen from navigationDrawerMenu
and true
when is choosen within fragment (move from MainFragmentCategory
to DetialFragmentCategory
) or click profilePhoto
in navigationDrawer
.
fragmentPopped
is always false
, why is that so? Even if I click profilePhoto
and again profilePhoto
in navigationDrawer
. It should avoid to add it to backStack for a second (and third, and fourth...) time, but it didn't.
Any idea how can I make it right?
Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.
Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
These 2 operations are what is saved as a Backstack record / transaction. Note that fragment A remains in created state, and its view is destroyed. Now popBackStack() reverses your last transaction that you've added to BackStack.
You can add the following code before you replace your fragment.
// Replace fragmentCotainer with your container id
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragmentCotainer);
// Return if the class are the same
if(currentFragment.getClass().equals(fragment.getClass())) return;
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