Search code examples
androidandroid-fragmentsandroid-viewpager

FragmentStatePagerAdapter return wrong position but right fragment


I have an Activity called MainActivity which has a ViewPager and a TabLayout. The ViewPager has 4 (four) fragments that bound there. I have a problem about (maybe) FragmentStatePagerAdapter

I have my code run

public class MainPagerAdapter extends FragmentStatePagerAdapter {

    Fragment[] fragments;

    public MainPagerAdapter(FragmentManager fm) {
        super(fm);
        fragments = new Fragment[]{
                new FragProfile(),
                new FragScore(),
                new FragMoney(),
                new FragOther()
        };
    }

    @Override
    public Fragment getItem(int p) {
        Log.w("Fragment", String.valueOf(p));

        switch (p){
            case 0:
                return fragments[0];
            case 1:
                return fragments[1];
            case 2:
                return fragments[2];
            case 3:
                return fragments[3];
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return 4;
    }
}

on first tab, i got this log came out

09-10 20:05:29.683 17034-17034/ampersanda.elsys W/Fragment: 0
09-10 20:05:29.684 17034-17034/ampersanda.elsys W/Fragment: 1

on second

09-10 20:11:03.970 17034-17034/ampersanda.elsys W/Fragment: 2

on third

09-10 20:11:54.534 17034-17034/ampersanda.elsys W/Fragment: 3

but on fourth i got nothing logged, and I back to the third i got this

09-10 20:14:07.373 17034-17034/ampersanda.elsys W/Fragment: 1

Back to second

09-10 20:14:50.241 17034-17034/ampersanda.elsys W/Fragment: 0

and I back to the first, i got nothing logged again

my code doesn't run well, but I got Fragment shows like its switch() but not about code inside it


Solution

  • In your case you should use FragmentPagerAdapter because when you use FragmentStatePagerAdapter the pages may get destroyed, so you will need to recreate them in getItem().

    This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment.