Activity and Fragment Lifecycles and Orientation Changes

后端 未结 2 547
失恋的感觉
失恋的感觉 2021-02-05 16:26

I have been having very odd issues with Fragments and orientation changes that have been causing force closes and not following a logical pattern.

I created

2条回答
  •  感动是毒
    2021-02-05 16:51

    It is because you are adding the fragment again and again in activity is recreated. You can use the below code in activity's onCreate method to avoid recreation of fragment:

    if(savedInstanceState == null) 
    {
        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    
        FragmentOne fragment = new FragmentOne();
    
        fragmentTransaction.add(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
    }
    

    When a config change occurs the old Fragment isn't destroyed -- it adds itself back to the Activity when it's recreated.

提交回复
热议问题