Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resuming a previous fragment onBackPressed()?

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.

like image 907
u3l Avatar asked Jun 30 '14 10:06

u3l


People also ask

How do you resume an existing Backstack fragment?

Declaring and initializing: Fragment A = new AFragment(); Fragment B = new BFragment(); Fragment C = new CFragment();

How can I maintain fragment state when added to the back stack?

Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.


1 Answers

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();
like image 136
Apoorv Avatar answered Sep 23 '22 16:09

Apoorv