OnCreateView called multiple times / Working with ActionBar and Fragments

前端 未结 2 1884
名媛妹妹
名媛妹妹 2020-12-01 00:00

I switched part of my App from Activities to Fragments so that I can use the neat ActionBar tabs.

However, after completing the transition I ran into an issue: whene

相关标签:
2条回答
  • 2020-12-01 00:31

    There is the show/hide option just so the fragments would not need to be repainted/recreated and the onCreate() and onCreateView() won't be reinvoked.

    0 讨论(0)
  • 2020-12-01 00:39

    When you call FragmentTransaction.replace(...), Android will effectively perform a sequence of FragmentTransaction.remove(...) (for all Fragments currently added to that container) and FragmentTransaction.add(...) (for your supplied Fragment). Removing a Fragment from the FragmentManager will cause the Fragment to be destroyed and its state will no longer be managed. Most noticeably, when you re-add the Fragment all of the views will have been reset. Note: since you are reusing the same Fragment instance, the Fragment will still keep the value any instance variables.

    One solution to this problem would be to use FragmentTransaction.detach(Fragment) and FragmentTransaction.attach(Fragment) when switching. This will cause the Fragment views to be recreated (onDestroyView() & onCreateView() will be called), but the instance state bundle will be saved and given back to you between calls and so the view state can be maintained. This is the approach taken by FragmentPagerAdapter when it tries to switch between Fragments.

    Alternatively, you could allow the Fragments to be destroyed, but maintain their saved state for them independently. This would use less memory, at the expense of a slower switching time. Methods of note would be FragmentManager.saveFragmentInstanceState(Fragment) and FragmentManager.setInitialSavedState(Fragment.SavedState), in conjuction with adding/removing. This is the approach taken by FragmentStatePagerAdapter.

    You can have a look at the source for FragmentPagerAdapter and the source for FragmentStatePagerAdapter for implementation hints.

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