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.
Declaring and initializing: Fragment A = new AFragment(); Fragment B = new BFragment(); Fragment C = new CFragment();
Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With