Remove old Fragment from fragment manager

后端 未结 5 1872
孤城傲影
孤城傲影 2020-11-27 15:26

I\'m trying to learn how to use Fragments in android. I\'m trying to remove old fragment when new fragment is calling in android.

5条回答
  •  自闭症患者
    2020-11-27 16:02

    Probably you instance old fragment it is keeping a reference. See this interesting article Memory leaks in Android — identify, treat and avoid

    If you use addToBackStack, this keeps a reference to instance fragment avoiding to Garbage Collector erase the instance. The instance remains in fragments list in fragment manager. You can see the list by

    ArrayList fragmentList = fragmentManager.getFragments();

    The next code is not the best solution (because don´t remove the old fragment instance in order to avoid memory leaks) but removes the old fragment from fragmentManger fragment list

    int index = fragmentManager.getFragments().indexOf(oldFragment);
    fragmentManager.getFragments().set(index, null);
    

    You cannot remove the entry in the arrayList because apparenly FragmentManager works with index ArrayList to get fragment.

    I usually use this code for working with fragmentManager

    public void replaceFragment(Fragment fragment, Bundle bundle) {
    
        if (bundle != null)
            fragment.setArguments(bundle);
    
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());
    
        //if oldFragment already exits in fragmentManager use it
        if (oldFragment != null) {
            fragment = oldFragment;
        }
    
        fragmentTransaction.replace(R.id.frame_content_main, fragment, fragment.getClass().getName());
    
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    
        fragmentTransaction.commit();
    }
    

提交回复
热议问题