简体   繁体   中英

FragmentPagerAdapter Fragment getItem wrong position?

So for some reason i'm getting a wrong position when i switch tabs on my tabbed activity.

At the bottom of my post you can see my logcat when i start my app, tab 1 and tab 2 their oncreateview is called.

And position 0 switches to 1 even though i'm on tab 1 which must be position 0.

So my problem is that when i change a tab, the wrong data is shown and wrong logcat info.

for example i change to tab 2, logcat shows oncreateview i called from tab3 ?

How can i fix this?

Thanks,

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    private int numOfTabs;

    SectionsPagerAdapter(FragmentManager fm, int numOfTabs) {
        super(fm);
        this.numOfTabs = numOfTabs;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                Log.e(TAG, "Pos: "+ position);
                return new Tab1();
            case 1:
                Log.e(TAG, "Pos: "+ position);
                return new Tab2();
            case 2:
                Log.e(TAG, "Pos: "+ position);
                return new Tab3();
            case 3:
                Log.e(TAG, "Pos: "+ position);
                return new Tab4();
            case 4:
                Log.e(TAG, "Pos: "+ position);
                return new Tab5();
                default:
                    return null;
        }
    }

    @Override
    public int getCount() {
        // Get total pages
        return numOfTabs;
    }
}

Logcat

 .activities.MainActivity: Pos: 0
 .activities.MainActivity: Pos: 1
 .fragments.Tab1: onCreateView called!
 .fragments.Tab2: onCreateView called!

ViewPager by default loads 2 tabs. So getItem gets called twice when you first open the app. When you go to tab2, ViewPager loads tab3 in advance so that the scroll will be smooth. See offscreenPageLimit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM