Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

android - Prevent ViewPager from destroying off-screen views

I have a ViewPager hooked up to a FragmentPagerAdapter that's displaying three fragments. The ViewPager appears to destroy a hosted fragment's view when it is more than one swipe away from the current position.

These views are all simple lists and this optimization is completely unnecessary, so I'd like to disable it. It's causing some visual problems because the lists have layout animations applied to them and those animations are being replayed after they've been destroyed and recreated. It also shows the scrollbar intro animation each time (where the scrollbar is briefly visible to indicate that scrolling is possible) which can be distracting, and the user's current scroll position is lost in the process.

It also doesn't load the third fragment until the first swipe happens, which is problematic because each fragment handles its own service calls and I'd prefer to have all three fire off at the same time when the activity loads. Having the third service call delayed is less than ideal.

Is there any way to convince ViewPager to stop this behavior and just keep all my fragments in memory?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In revision 4 of the Support Package, a method was added to ViewPager which allows you to specify the number of offscreen pages to use, rather than the default which is 1.

In your case, you want to specify 2, so that when you are on the third page, the first one is not destroyed, and vice-versa.

mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...