Ackman Ackman - 1 year ago 74
Android Question

How to navigate to previous fragment of previous activity

I have a main activity A with 4 fragments on top of it. The fragments appear one after the other on button click.

After I click button on last fragment (fourth), I am taken to a new activity B.

How can I implement back button press as such when user clicks on it. He is taken to the fourth fragment of Activity A?

Answer Source

You need to use the back stack for this. Each time you add a change fragments you will want to add that fragment to the back stack.

//Create an instance of your fragment;
MyFragment frag = MyFragment.newInstance();
//replace the fragment in a normal fragment transaction
                .replace(, frag, "MyFragment Tag")
                //add to the back stack 

The thing about this, is now the back button will traverse through each of your previous fragments. So after hitting fragment 3, if you hit the back button, you will see fragment 2, etc.

This may not be your desired result, so you may only want to add a the fragment to the back stack when you add fragment 4.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download