Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentPagerAdapter - avoid recreation of fragments' views

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 Timers 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.

like image 636
Beowulf Bjornson Avatar asked Nov 27 '11 09:11

Beowulf Bjornson


2 Answers

The following method should prevent the fragments from destroying:

mViewPager.setOffscreenPageLimit(no_of_fragments_to_be_kept_offscreen);
like image 153
Saimon Avatar answered Nov 15 '22 09:11

Saimon


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);
like image 21
Raymond Chenon Avatar answered Nov 15 '22 08:11

Raymond Chenon