FragmentPagerAdapter - avoid re-creating fragments

I noticed that when using FragmentPagerAdapterFragments that are not adjacent to the current, they destroy their representations (and their methods are called onPause()and onStop(), and strangely is onSaveInstanceState(Bundle)not), and onCreateViewagain called for these fragments. My problem is that I have several Timerworking on these fragments, and their recreation is not viable, because these timers must start and update the corresponding fragment of the interface. For large screens I used HorizontalScrollViewwith LinearLayout, and it works flawlessly.

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();
        }
    }
}

Activity onCreate, , , .

ViewPager HorizontalScrollView ? , , "" .

+5
4

:

mViewPager.setOffscreenPageLimit(no_of_fragments_to_be_kept_offscreen);
+16

FragmentPagerAdapter 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);
+6

FragmentStatePagerAdapter FragmentPagerAdapter. onCreate (Bundle savedInstanceState) .

0
source

You need to set a limit on the pager to avoid viewing.

your_pager_obj.setOffscreenPageLimit(no_of_fragments_on_each_side_of_the_current_fragment);
0
source

All Articles