Activity and Fragment Lifecycles and Orientation Changes

后端 未结 2 511
失恋的感觉
失恋的感觉 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.

    0 讨论(0)
  • 2021-02-05 16:55

    This happens because the activity calls onSaveInstanceState(Bundle) before being destroyed. By default, the activity is saving the states of its fragments in this method.

    Later, when the activity is re-created, the old fragments are re-created in the activity onCreate(Bundle savedInstanceState) method.

    You might want to check the source code here and here to better understand this behaviour.

    0 讨论(0)
提交回复
热议问题