I have four Fragments: A, B, C, D. Now I am moving from A --> B so my code will be
from A to B
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new B())
.addToBackStack("A")
.commit();
Now from B to C so code will be
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new C())
.addToBackStack("B")
.commit();
Now from C to D. But I don't want to include C in backstack because on back press I don't want C fragment to be shown.
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new D())
.commit();
Now when I press Back button it will work perfectly upto A. Now if I repeat same process again. Now again on back press From D Fragment, I will be sent directly on A fragment instead of B fragment. Can you please figure it out the mistake that I am doing in above code?
You have to provide same String value for addToBackStack for single Stack.
.replace(R.id.content_frame, new B())
.addToBackStack("stack")
.replace(R.id.content_frame, new C())
.addToBackStack("stack")
Here is the code of BackStackChangedListener.
public static void performNoBackStackTransaction( final FragmentManager fragmentManager, String tag, Fragment fragment) {
final int newBackStackLength = fragmentManager.getBackStackEntryCount() +1;
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment, tag)
.addToBackStack(tag)
.commit();
fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
int nowCount = fragmentManager.getBackStackEntryCount();
if (newBackStackLength != nowCount) {
// we don't really care if going back or forward. we already performed the logic here.
fragmentManager.removeOnBackStackChangedListener(this);
if ( newBackStackLength > nowCount ) { // user pressed back
fragmentManager.popBackStackImmediate();
}
}
}
});
}