Why do you check for savedInstanceState == null when adding fragment?

后端 未结 1 1681
梦谈多话
梦谈多话 2021-02-07 02:52

In the fragment doc, in one of the example, they check for savedInstanceState == null when adding a fragment:

public static class DetailsActivity ex         


        
相关标签:
1条回答
  • 2021-02-07 03:48

    What is the purpose of this check?

    To not add the fragment twice, though I prefer checking to see if the fragment is there instead of relying on that Bundle being null.

    What would happen if it is not there?

    Initially, nothing, as the Bundle will be null when the activity is first created.

    However, then, the user rotates the device's screen from portrait to landscape. Or, the user changes languages. Or, the user puts the device into a manufacturer-supplied car dock. Or, the user does any other configuration change.

    Your activity will be destroyed and recreated by default. Your fragments will also be destroyed and recreated by default (exception: those on which setRetainInstance(true) are called, which are detached from the old activity and attached to the new one).

    So, the second time the activity is created -- the instance created as a result of the configuration change -- your fragment already exists, as it was either recreated or retained. You don't want a second instance of that fragment (usually), and therefore you take steps to detect that this has occurred and not run a fresh FragmentTransaction.

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