简体   繁体   English

FragmentPagerAdapter Fragment getItem位置错误?

[英]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. 在我的文章底部,您可以在启动应用程序时看到我的logcat,分别称为选项卡1和选项卡2的oncreateview。

And position 0 switches to 1 even though i'm on tab 1 which must be position 0. 即使我位于必须位于位置0的选项卡1上,位置0也会切换为1。

So my problem is that when i change a tab, the wrong data is shown and wrong logcat info. 所以我的问题是,当我更改选项卡时,将显示错误的数据和错误的logcat信息。

for example i change to tab 2, logcat shows oncreateview i called from tab3 ? 例如,我更改为选项卡2,logcat显示我从tab3调用的oncreateview吗?

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 logcat的

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

ViewPager by default loads 2 tabs. ViewPager默认情况下会加载2个标签。 So getItem gets called twice when you first open the app. 因此,第一次打开应用程序时,getItem会被调用两次。 When you go to tab2, ViewPager loads tab3 in advance so that the scroll will be smooth. 当您转到tab2时,ViewPager会预先加载tab3,以便滚动平滑。 See offscreenPageLimit . 参见offscreenPageLimit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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