Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment re-created when change tab with ViewPager

I've got a ViewPager with 4 tabs.

I'm using a custom adapter that extends FragmentPagerAdapter.

The problem is that when I change the tab, the first Fragment gets created again although it's not the currently visible. Moreover, this only happens after changing the tab for the fourth time. E.g. tab1 -> tab2 -> tab3=> onStop from tab1 is called. -> tab2 => onCreateView from tab1 is called (onAttach is not called).

I want to avoid this. I need all tabs to remain always in their state even when they are not currently displayed. How can I do this?

like image 649
sergi Avatar asked Jan 04 '13 13:01

sergi


2 Answers

It's been as easy as using method setOffscreenPageLimit() from ViewPager.

More info: http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)

like image 114
sergi Avatar answered Nov 09 '22 08:11

sergi


Viewpager has one public method named setOffScreenPageLimit which indicates the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state.

Activity:

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

...

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = findViewById(R.id.container);
        mViewPager.setOffscreenPageLimit(3);  // change your number here
        mViewPager.setAdapter(mSectionsPagerAdapter);
like image 39
live-love Avatar answered Nov 09 '22 09:11

live-love