3

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.

Kai
  • 38,985
  • 14
  • 88
  • 103
Jack
  • 2,043
  • 7
  • 40
  • 69

3 Answers3

3

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

Community
  • 1
  • 1
jos
  • 1,070
  • 12
  • 22
0

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

Community
  • 1
  • 1
reactivemobile
  • 505
  • 3
  • 9
0

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!!