Fragment Addtobackstack() And Popbackstackimmediate() Not Working
Solution 1:
For those, who are still looking for solution.
In the main Activity
class (which is hosting the fragments)just override onBackPressed()
.
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
There is no onBackPressed()
method in fragment, and this method is just for the activity
. So,when we press the back key, the default behaviour of activity
is shown, which is
you will either go to previous activity(if there is any) or the app will exit.
Now we need to override this method to tell the activity
that when we press the back key, if there are any fragments in back stack, pop them out (and this is when the addToBackStack()
comes into picture). Otherwise follow the default behaviour.
Solution 2:
Try this (Note add not replace for fragmentA, and addToBackStack() for fragmentB)
StopItemFragment list = StopItemFragment.newInstance(null); //A - extends ListFragment
fragmentManager.beginTransaction()
.add(R.id.content_frame, list)
.commit();
and
StopFragmentfragment= StopFragment.newInstance(null, null); //B - extends Fragment
...
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack("FragmentB")
.commit();
Solution 3:
I had to call beginTransaction()
and commit()
of FragmentManager
manually.
Solved by overriding onBackPressed()
:
@Override
public void onBackPressed() {
...
if (fragmentManager.getBackStackEntryCount() > 1){
fragmentManager.popBackStackImmediate();
fragmentManager.beginTransaction().commit();
} else {
//handle finishfinish(); // Closes app
}
}
Solution 4:
If you are Struggling with addToBackStack() & popBackStack() then simply use
FragmentTransactionft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, newHomeFragment(), "Home");
ft.commit();`
In your Activity In OnBackPressed() find out fargment by tag and then do your stuff
Fragmenthome= getSupportFragmentManager().findFragmentByTag("Home");
if (home instanceof HomeFragment && home.isVisible()) {
// do you stuff
}
For more Information https://github.com/DattaHujare/NavigationDrawer I never use addToBackStack() for handling fragment.
Solution 5:
the reason why the popBackStack()
and popBackStackImmediatly()
is due to the fact that you didnt add that fragment (that you want to pop) to the backStack. In order to do this you have to make a call to addToBackStack() at the moment of making the transaction to add/replace your fragment.
Post a Comment for "Fragment Addtobackstack() And Popbackstackimmediate() Not Working"