Lisa Wray Lisa Wray - 1 year ago 65
Android Question

Prevent ViewPager from always instantiating Fragment at position 0?

I'm using a

, and the default starting page is 0. I want mine to start on some arbitary page, say 5. This is how I display my ViewPager:

viewPager.setCurrentItem(viewNumber, true);

However, the ViewPager is first created at the default position (0), then switched to my desired position (5). So my fragments are created in this order: 0, 1, 4, 5, 6.

I don't want the fragments at 0 and 1 created at all. How can I achieve this?

Answer Source

How can I achieve this?

Copy the source code of ViewPager into your project, refactor it into your own package, and modify the code to suit. Specifically, you would need to modify setAdapter() to not attempt to lay out or populate the ViewPager, until you manually request that by some new method (e.g., lisaWouldLikeYouToPopulateNowKThxBye()).

You might be able to get away with subclassing ViewPager and overriding populate() to not actually do its work based on some flag you hold in your subclass, so that you could avoid populating from your PagerAdapter until after your setCurrentItem() call.

Or, just leave it alone. It is unclear what benefits you perceive for doing this, let alone whether they would be worth the maintenance headache of your forked ViewPager.