Building fragment stack for One Activity Many Fragment App

596 views Asked by At

My App has only one activity and lots of fragments.

In my activty's XML, I just have a FrameLayout on which I replace/add/hide/show various fragments.

Imagine Fragment A is the first fragment the user sees when they open the app.

Click something in Fragment A to launch Fragment B and click something in Fragment B to launch Fragment C.

So the navigation is can be illustrated as follows :

Fragment A --> Fragment B --> Fragment C

I want to launch the app and show Fragment C directly from notification.

However, how can I provide back navigation from Fragment C, as such clicking back would go to Fragment B and clicking back again go to Fragment A ?

i.e How can I inject the following stack structure ?

Fragment A <-- Fragment B <-- Fragment C

2

There are 2 answers

0
gabin On BEST ANSWER

Yes, you can do this. Since support library v26 you can build the stack with fragments without significant cost. In your activity make the following:

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentA())
            .addToBackStack("fragmentA")
            .setReorderingAllowed(true)
            .commit();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentB())
            .addToBackStack("fragmentB")
            .setReorderingAllowed(true)
            .commit();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentC())
            .addToBackStack("fragmentC")
            .setReorderingAllowed(true)
            .commit();

Keep in mind that FragmentA and FragmentB will behave in a bit different way after pressing back on FragmentC due to setReorderingAllowed. onCreateView won't be called for FragmentA and FragmentB after they were added to stack, only in FragmentC onCreateView will be called. For FragmentA and FragmentB only onCreate will be called.

7
Vaibhav Sharma On

What you can do is - Use a notification intent in which you pass a string. In your main activity if you receive that string make a fragment stack of A, B and C. Else if you don't get the intent just continue your flow as it is.