-1

I am still a new App developer and trying out my first app.

I have an app that has a main activity with three menu buttons and one button leads to a fragment and within that fragment, there is another button that creates and shows another fragment. So it is like this Activity -> Fragment1 -> Fragment2 I'm trying to navigate from Fragment2 to Fragment 1 using back button. I used getActivity().onBackPressed(). The problem is that when it should just navigate back to Fragment 1, it just leaps all the way back to Activity.

What method do I need to override or use just to navigate back from F2 to F1?

Thank you in advance.

Cal
  • 27
  • 8

1 Answers1

0

When you are adding fragment, add them to backStack as well. This will allow you to play around already added fragments as you can then deal with them in onBackPressed.

@Override
public void onBackPressed() {
    FragmentManager fragmentManager = getSupportFragmentManager();

if (fragmentManager.getBackStackEntryCount() < 1){
    Fragment fragment = new XXXFragment();
    FragmentTransaction fragmentTransaction =    
    getSupportFragmentManager().beginTransaction();

    getSupportActionBar().setTitle(mDrawerTitle);

    fragmentTransaction.replace(R.id.frame_container, 
    fragment).addToBackStack("first").commit();

}else{
    finish();
}
}
Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49