Why is my fragment onCreate being called extensively whenever I page through my applications viewPager?

后端 未结 2 1232
小蘑菇
小蘑菇 2021-02-15 11:59

I\'m not quite understanding this fragment lifecycle business.

I have a pretty standard 3 page horizontal slider view Pager layout for a \"view details\" section of my a

相关标签:
2条回答
  • 2021-02-15 12:52

    ViewPager is quite zealous in shutting down things it isn't currently using, and this is exactly what is happening here. The default behaviour is for ViewPager to "keep around" one page either side of the page being viewed, and destroy the rest. Hence in your 3-page view, page 3 gets destroyed when selecting page 1, then when page 2 is reselected page 3 is recreated. As you've noticed, page 2 only has onCreate(..) called once because it is always adjacent to, or is, the currently selected page.

    To solve this, simply set ViewPager.setOffscreenPageLimit(2). Then the ViewPager will keep all your Fragments. Obviously this isn't a good idea for a large number of Fragments, but for your case it should be fine.

    0 讨论(0)
  • 2021-02-15 13:03

    @Espiandev's solution will work for your current case, but you're right that your state is the issue. You should use the setArgument and/or onSaveInstanceState methods to save your Fragment's state (which shouldn't be too hard, since e.g., a response from the server can usually be represented as a String), and then use getArgument and/or the Bundle passed in onCreate to restore it.

    Alternatively, you could have your Activity do the server fetches, and then call setArgument for each of your fragments, and check the arguments inside your Fragment to determine if your data has arrived yet (and if not, potentially display a loading state of some kind).

    If you care at all about screen orientation change, this related question will also be useful to you.

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