Resuming a previous fragment onBackPressed()?

u3l picture u3l · Jun 30, 2014 · Viewed 14.2k times · Source

I have a HomeFragment that has a button, which when clicked calls the following:

Fragment frag = new CustFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.home_container, frag).commit();

Then in my FragmentActivity which is the fragments mentioned above, I have:

@Override
public void onBackPressed() {

    getFragmentManager().popBackStack();
    super.onBackPressed();

}

That's what I've tried, but if I'm on the frag fragment and I press the back button, it doesn't go back to the last fragment (the HomeFragment). Instead, it attempts to go back to the last Activity, but since there is none (i.e. the previous activity had finish() invoked on it), it just goes to the Android Home Screen.

What am I doing wrong?

PS: If I'm being unclear, just comment below and i'll try to clarify.

Answer

Apoorv picture Apoorv · Jun 30, 2014

Change

@Override
public void onBackPressed() 
{
   getFragmentManager().popBackStack();
   super.onBackPressed();
}

to

@Override
public void onBackPressed() 
{
  if(getSupportFragmentManager().getBackStackEntryCount() > 0)
    getSupportFragmentManager().popBackStack();
  else
   super.onBackPressed();
}

and

fragmentManager.beginTransaction().replace(R.id.home_container, frag).commit();

to

fragmentManager.beginTransaction().replace(R.id.home_container, frag).addToBackStack(null).commit();