AddToBackstack does not work when replacing fragments
I am having a problem where I call addToBackStack
into my fragment when it is replaced, but when I click back to return to that fragment it does not come back, it just closes my application.
Fragment fragmentWebView = new MyWebView();
transaction.replace(R.id.content_frame, fragmentWebView);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
Am I doing something wrong here? everything looks good to me.
Try adding this code to your activity
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Viewed here
Hope it helps
I'm not sure if this is related, but you shouldn't be building your snippet with new
, see fooobar.com/questions/14216 / ...
You have to call addToBackStack (MyWebView.class.getName ()); and it is recommended to check if your fragment exists. The closing transaction could be something like this:
Fragment fragmentWebView = getFragmentManager().findFragmentByTag(MyWebView.class.getName());
if (fragmentWebView == null)
fragmentWebView = new MyWebView();
transaction.replace(R.id.content_frame, fragmentWebView, MyWebView.class.getName());
transaction.addToBackStack(MyWebView.class.getName());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
Now you can identify your fragment using the (MyWebView.class.getName ()) tag. Hope this helps you!