Skip to content

Instantly share code, notes, and snippets.

@vekexasia
Last active January 8, 2020 19:39
Show Gist options
  • Save vekexasia/42416bd889fe269b4eba to your computer and use it in GitHub Desktop.
Save vekexasia/42416bd889fe269b4eba to your computer and use it in GitHub Desktop.
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
Copy link

nrazon commented Oct 23, 2015

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

@yilmaz-gokhan
Copy link

Can u share an example project about this solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment