How to move back to previous fragment from current fragment?
Fragments are useful in replacing parts of activity layout with different layouts. When creating a new instance of the fragment, replace the FrameLayout
with the fragment.
On clicking the back button in an activity with multiple fragments, it will return you to the previous activity and not the previous fragment. So, in order to return to the previous fragement, you need to add it to the back stack:
fragmentTransaction.addToBackStack(null);
Below is the entire code for replacing the FrameLayout
with the fragment in an activity:
// Create a new instance of your fragment class here by calling an empty constructor Fragment = new HomeFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); // Replace the FrameLayout with the fragment fragmentTransaction.replace(R.id.frame_container, fragment); // Add to Back stack so that you can return to previous fragment fragmentTransaction.addToBackStack(null); // Commit the transaction to show the Fragment fragmentTransaction.commit();
However, do not add the first fragmentTransaction
to the back stack. If you do this, you will get a white screen on pressing back button before the first fragment.