My scenario : Activity 1 consists of Fragments A-> B-> C. All the fragments are added using this code :
FragmentManager fm = getSupportFragmentManager()
This is how I do it..
With FragmentA.java and any other fragments.
Replace your fragment with its class name as tag:
private void showFragment(Fragment fragment){
if(fragment != null){
getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment,fragment.getClass().getSimpleName()).commit();
}
}
Now in onBackPressed():
@Override
public void onBackPressed()
{
if(getSupportFragmentManager().findFragmentByTag("FragmentA") == null)
showFragment(new FragmentA());
else
super.onBackPressed();
}