Luca93
Luca93

Reputation: 91

Fragment Navigation (BackStack)

My Application has one Activity with a layout (FrameLayout) for many fragments.

Here is a graphical explanation: enter image description here

I want to be able to go back to "CamFragment(B)" from "InfoPlaceFragment(C)", and to go back to "PlacesFragment(A)" from "CamFragment(B)".

------- EDIT -------

SOLUTION:

In the "MainActivity.java":

onPlaceParse() // This method is called when the data from the server is received:

  // Here I create the "PlaceFragment"
  fManager = getSupportFragmentManager();
  fragmentPlaces = new PlacesFragment();

  fManager.beginTransaction()
     .replace(R.id.fragment_list_container, fragmentPlaces)
     .commit();

onResortSelected // This method is called when the resort is selected

   fragmentCams = new CamsFragment();

   fManager.beginTransaction()
    .replace(R.id.fragment_list_container, fragmentCams)
    .addToBackStack(null)
    .commit();

onButtonInfoSelected // This method is called when the btn info is selected

    fragmentInfo = new InfoResortFragment();

    fManager = getSupportFragmentManager();
    fManager.beginTransaction()
        .replace(R.id.fragment_list_container, fragmentInfo, "Info")
                    .addToBackStack(null)
        .commit();

When you press the back button, if you are in the "Info Fragment" it returns to "PlaceFragment" and if you are in the "CamsFragment" it returns to "PlacesFragment".

Upvotes: 0

Views: 951

Answers (2)

aromero
aromero

Reputation: 25761

This is possible, you need to call addToBackStack(null) in the fragment transactions.

Reference: Providing Proper Back Navigation

Upvotes: 2

Scott W
Scott W

Reputation: 9872

When you create your FragmentTransaction that will add/remove/replace (or whatever pattern you are using) the Fragments, just make sure to call addToBackStack(). Then, when the user presses the back button, the system will automatically cycle back through the entries added to the back stack, in reverse order from how they were originally added. No additional work is required on your part! :)

Upvotes: 1

Related Questions