Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fragment-back-nightmare-post
// the back is equivalent to (removed boilerplate)
fm.beginTransaction()
.remove(bFragment)
.add(aFragment)
.commit();
// After A -> B -> C (back [A,C] shown)
// user goes to B with this transaction
fm.beginTransaction()
.replace(R.id.content, new B_Fragment(), "fragment-b")
.addToBackStack("a")
.commit();
// which is the same as
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.content))
.add(R.id.content, new B_Fragment(), "fragment-b")
.addToBackStack("a")
.commit();
public static void performNoBackStackTransaction(FragmentManager fragmentManager, String tag, Fragment fragment) {
final int newBackStackLength = fragmentManager.getBackStackEntryCount() +1;
fragmentManager.beginTransaction()
.replace(R.id.content, 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();
}
}
}
});
}
//fm is FragmentManager
// Fragment a is on the screen
Fragment a = new A_Fragment()
fm.beginTransaction()
.remove(null /*no fragments in R.id.content*/)
.add(R.id.content, aFragment, "fragment-a")
.commit();
// user wants to go from A to B
Fragment bFragment = new B_Fragment();
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.content)) // resolves to A_Fragment instance
.add(R.id.content, bFragment, "fragment-b")
.addToBackStack("a")
.commit();
// user wants to go from B to C
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.content)) // resolves to B_Fragment instance
.add(R.id.content, new C_Fragment(), "fragment-c")
.commit();
//fm is FragmentManager
// Fragment a is on the screen
fm.beginTransaction()
.replace(R.id.content, new A_Fragment(), "fragment-a")
.commit();
// user wants to go from A to B
fm.beginTransaction()
.replace(R.id.content, new B_Fragment(), "fragment-b")
.addToBackStack("a")
.commit();
// user wants to go from B to C
fm.beginTransaction()
.replace(R.id.content, new C_Fragment(), "fragment-c")
.commit();
@nrazon

This comment has been minimized.

Copy link

commented Oct 23, 2015

Thanks for performNoBackStackTransaction solution. Saved my life. I was looking for a solution for months! Works perfect!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.