Reputation: 3412
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.
Upvotes: 8
Views: 16428
Reputation: 24012
You can use:
fragmentTransaction.addToBackStack(null);
and no need to take care of onBackPressed()
.
BTW in your onBackPressed()
super.onBackPressed()
means you are actually changing nothing.
It should have been something like:
if(currentFragmentIsCustFragment){
getSupportFragmentManager().popBackStack();
}else{
super.onBackPressed();
}
Upvotes: 1
Reputation: 13520
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();
Upvotes: 11
Reputation: 14590
Add your fragment to back stack using addToBackStack(null)
like..
fragmentManager.beginTransaction().replace(R.id.home_container, frag).addToBackStack(null).commit();
Upvotes: 3
Reputation: 3503
beginTransaction creates a new FragmentTransaction. It has a method addToBackstack. If you call it before you commit your transaction you can remove your overridden onBackPressed completely. Reference
Upvotes: 1