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?
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 getSupportFragmentManager().beginTransaction() .replace(R.id.container, frag, "MyFragment Tag") //add to the back stack .addToBackStack(f) .commit();
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.