I am using Android\'s support.v4
package to develop a ViewPager containing multiple Fragment
s.
I am trying to hide the Views when the user
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 Fragment
s even when they are not in focus.
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.