ViewPager Fragments getting destroyed over time?

后端 未结 2 1725
夕颜
夕颜 2020-12-23 18:08

I am using Android\'s support.v4 package to develop a ViewPager containing multiple Fragments.

I am trying to hide the Views when the user

相关标签:
2条回答
  • 2020-12-23 18:32

    Add the following when you initialize your ViewPager,

    mPager.setOffscreenPageLimit(NUM_ITEMS-1);
    

    In your case, this will set the number of off-screen pages to 1 (i.e. it will keep the additional off-screen page in memory when the other page is currently in focus). This will force your ViewPager to keep all of the Fragments even when they are not in focus.

    0 讨论(0)
  • 2020-12-23 18:42

    I examined your code and I think the issue is that in onPageScrolled, you're calling getItem. This implementation (which is actually like most implementations of it on web) returns a new instance each time. However, most examples I've seen don't call getItem, so this is usually alright.

    In your case, I would hold lazily create the Fragment in getItem: if it doesn't exist for that position, then create it, and then hang onto it in an ArrayList or some other collection, but if it already exists, just return it from that collection.

    Otherwise, you create a fragment instance A, then scroll to another fragment instance B. You try to tell fragment instance A to clean up some views, but you wind up telling a new fragment instance C to do so. It hasn't had a chance to set up its own views yet, so you're getting the null pointer to charts.

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