Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments in ViewPager get recreated

I have a FragmentActivity with container, where I put Fragment with ViewPager. In ViewPager I have 3 Fragments:

[MainActivity]
    [ViewPagerFragment]
        [Fragment1][Fragment2][Fragment3]

When the user clicks a button on Fragment1/Fragment2/Fragment3, I replace the ViewPagerFragment with OtherFragment, so the hierarchy looks like this:

[MainActivity]
    [OtherFragment]

When I hit Back button, ViewPagerFragment gets recreated, as well as its nested Fragments (Fragment1/Fragment2/Fragment3).

Is there a way to save the state of ViewPagerFragment and its nested fragments? So that the fragments will keep their state and not get recreated?

I have set setRetainInstance(true) for ViewPagerFragment, but seems like it doesn't take effect.

like image 664
agamov Avatar asked Mar 06 '13 11:03

agamov


1 Answers

Just set this :- where the argument is the number of fragments in the ViewPager

mViewPager.setOffscreenPageLimit(3);

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.

like image 142
Augustus Francis Avatar answered Nov 18 '22 05:11

Augustus Francis