Search code examples
javaandroidpagerslidingtabstrip

SlidingTabLayout, Restarts fragment On case 4 to 1?


my SlidingTabLayout restarts my fragment dashboard activity when switching from fragment tags to fragment dashboard, or position 4 to 0. Here is the code that I have written so far, can anyone shed some light on the situation ?

 public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        //2 steps creating a fragment, create the fragment class and create the UI for it
        Fragment fragment = null;
        //we dont want it to return our place holder Fragment instead we want to switch bewtween 3
        //create a switch case based on the position applied or the fragment selected
        switch (position) {
            case HOME:
                fragment = Dashboard.newInstance("","");
                break;
            case TAGS:
                fragment = Tags.newInstance("","");
                break;
            case MY_RECENT:
                fragment = MyPosts.newInstance("","");
                break;
            case TOP:
                fragment = Top.newInstance("", "");
                break;
        }
        return fragment;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Home";
            case 1:
                return "Top";
            case 2:
                return "Recent";
            case 3:
                return "Tags";
        }
        return null;
    }
}

Solution

  • You have to load all fragment in one time, you should call this method

    int size=4;
    viewPager.setOffscreenPageLimit(size);
    

    after set adapter, size is the no of fragment which you want to load first time