I noticed that when using a FragmentPagerAdapter
the Fragments that are non-adjacent to the current one are having their views destroyed (and their onPause()
and onStop()
methods called, and strangely onSaveInstanceState(Bundle)
isn't being called), and onCreateView
is being called again for these Fragments. My problem is that I have some Timer
s running on these Fragments, and recreating them isn't viable because these timers should fire and update the relevant fragment UI. For large screens I used a HorizontalScrollView
with a LinearLayout
and it works flawlessly.
The relevant code in my Activity:
private class MyPagerAdapter extends FragmentPagerAdapter implements TitleProvider {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
return mAddNewScenesFragment;
} else if (position == 1) {
return mGlobalEventsFragment;
} else {
return mSceneFragments.get(position - 2);
}
}
@Override
public int getCount() {
return mSceneFragments.size() + 2;
}
@Override
public String getTitle(int position) {
if (position == 0) {
return "New scene";
} else if (position == 1) {
return mGlobalEventsFragment.getTitle();
} else {
return mSceneFragments.get(position - 2).getTitle();
}
}
}
The fragments are created on the Activity's onCreate
method and others can be added to the list at runtime, but even without adding new ones, the third fragment is destroyed when I scroll to the first one.
Is there a way to avoid their destruction or should I just forget about ViewPager
and use a HorizontalScrollView
for small screens too? I choose to use it because I think the "fixed" behavior really helps with usability.
The following method should prevent the fragments from destroying:
mViewPager.setOffscreenPageLimit(no_of_fragments_to_be_kept_offscreen);
Instead of hacking FragmentPagerAdapter
, simply use ViewPager
.
int limit = myPagerAdapter.getCount();
// Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state.
viewpager.setOffscreenPageLimit(limit);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With