Android Lifecycle management of Fragments within ViewPager and FragmentPagerAdapter

前端 未结 3 799
迷失自我
迷失自我 2020-12-30 05:24

I have been struggling to find out what the correct management of Fragments within a FragmentActivity with a ViewPager is. Before I go into details

相关标签:
3条回答
  • 2020-12-30 05:40

    I believe that this question, about retrieving the current fragment from a ViewPager, will help you. As already pointed out, fragments are managed by the Fragment(State)PagerAdapter and NOT Activity's or Fragment's lifecycle.

    • The first time the activity is created, fragments are returned by the getItem method. This method is called only once per fragment, even if the activity gets recreated.
    • Subsequent times, the fragments are returned by the instantiateItem method. Most probably, this is the place, where you need to get hold of your fragments and call their refresh methods.
    0 讨论(0)
  • 2020-12-30 05:40

    How about adding this to Activity Tag in your manifest:

    android:configChanges="orientation"
    

    or this for API 13 or higher

    android:configChanges="orientation|screenSize" 
    

    so it won't recreate your fragments when it changes orientation..

    0 讨论(0)
  • 2020-12-30 05:55

    It's lot to read, but after reading just introduction and the question and having experience with FragmentStatePagerAdapter, which is similar to FragmentPagerAdapter I can tell you that:

    After rotation your adapter will AUTOMAGICALLY attach old fragments. So it seems that although activity creating adapter is being recreated, FragmentManager, which is global and it's instance preserve activity's recreation will detect that new FragmentStatePagerAdapter is combined with the same ViewPager and is asking for the same Fragments and will simply fetch them from Fragment's BackStack.

    You as designer of Fragments can notice this behavior by continues invocation of Fragment.onAttach() and Fragment.onDetach(). When onAttach() occurs it's either creation of your Fragment or reusing it after rotation. You should be able to distinguish that Fragment was rotated with use of callback onRestoreRnstanceState().

    You will see in your logs many onCreate() and other states logs simultaneously, because FragmentStatePagerAdapter always fetches/creates min 3 Fragments (except if you set that they are only 2 or 1), so also after screen rotation 3 fragments will be reattached from backstack.

    I hope that it helped.

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