简体   繁体   中英

Fragment Back Button Navigation

Suppose I have 3 Fragments: A,B,C

  1. I go from A -> B
  2. B -> C
  3. C -> B (without pressing back button)
  4. B -> C (without pressing back button)
  5. C -> B (without pressing back button)
  6. B -> C (without pressing back button)

Now by pressing Back Button, Navigation should be C->B->A -> finish

In other words, irrespective of number of navigation (without pressing back button) between B->C and C->B, back navigation by pressing back button should in order C->B->A

Assuming that all the allowed transitions are A<->B<->C, you can use FragmentManager.popBackStack() method when navigating C->B, and always add the transition to back stack when navigating B->C.

Here's how to do the transitions:

public void transitionFromAToB() {
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.fragment_container, new FragmentB())
            .addToBackStack(null)
            .commit();
}

public void transitionFromBToC() {
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.fragment_container, new FragmentC())
            .addToBackStack(null)
            .commit();

}

public void tansitionFromCToB() {
    getSupportFragmentManager().popBackStack();
}

public void transitionFromBToA() {
    getSupportFragmentManager().popBackStack();
}

So when transitioning C->B, you're not actually doing a new transition, you're actually just reversing the B->C transition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM