Search code examples
androidtabsandroid-viewpagerfragmentsliding

SlidingTabLayout with Fragments and ViewPager


I want to use SlidingTabLayout and have the contents be that of a fragment.

I tried this but obviously it's wrong.

    @Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = null;
    if(position == 0){
        fragment = new Fragment1();
    }
    else if(position == 1) {
        fragment = new Fragment2();
    return fragment;
}

What would be the best practice to do this? If it makes a difference, my fragments contain lists inside them


Solution

  • I would create an array of fragments inside a FragmentPagerAdapter so you can do something like this in the instantiateItem callback:

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
    if (mFragments[position] == null) { //mFragments is the array of Fragments
        mFragments[position] = new Fragment();
    }
    return mFragments[position];
    }
    

    This way you won't return return a new fragment each time you switch tabs