0

I have a Fragment with MapView in it. I add Fragment to container with following code:

    Fragment fragment = new MyLocationFragment()
    String tag= fragment.getClass().getName();

    FragmentTransaction transaction = fm.beginTransaction();
    transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left,
            R.anim.slide_in_left, R.anim.slide_out_right);
    transaction.replace(R.id.container, fragment, tag);
    transaction.addToBackStack(null);
    transaction.commit();

Now when user presses back, this Fragment is supposed to be removed from FragmentManager. But if execute this code :

    Fragment fragment = getSupportFragmentManager().findFragmentByTag(MyLocationFragment.class.getName());

It never returns null, even if I replace other fragments in same container. What can I do to remove Fragment from FragmentManager? Am I doing something wrong here ?

jimmy0251
  • 16,293
  • 10
  • 36
  • 39

1 Answers1

0

When an activity is destroyed, its FragmentManagersaves out its list of fragments. When the activity is recreated, the new FragmentManager retrieves the list and recreates the listed fragments to make everything as it was before.

[Refer to book "Android Programming The Big Nerd Ranch Guide" P150]

So your should remove fragment from fragmentmanager. Refer to this Q&A Remove old Fragment from fragment manager

Your question maybe duplicate with thisHow to get a Fragment to remove itself, i.e. its equivalent of finish()?

Community
  • 1
  • 1
Weiyi
  • 1,843
  • 2
  • 22
  • 34