Jack
Jack

Reputation: 2053

addToBackstack not working when replacing fragments

I am having an issue where I call addToBackStack on my fragment when replacing it, but when I press back to go back to that fragment, it doesn't go back, it just closes my app.

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 anything wrong here? everything looks fine to me.

Upvotes: 3

Views: 4080

Answers (3)

jos
jos

Reputation: 1070

Try to add this code to your activity

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0 ){
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

Watched here

Hope it helps

Upvotes: 3

You should call addToBackStack(MyWebView.class.getName()); and it is recommended that you check if your fragment exist. The complet 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 by a tag (MyWebView.class.getName()). Hope it helps you!!

Upvotes: 0

reactivemobile
reactivemobile

Reputation: 505

I'm not sure if it's related but you shouldn't create your fragment using new, see this post on StackOverflow

Upvotes: 0

Related Questions