FragmentStatePagerAdapter returns wrong positions

2019-09-14 00:21发布

问题:

I'm using a FragmentStatePagerAdapter. The getItem(int position) returns wrong positions. I have 5 fragments. This is the position when I change the fragments:

Fragment0 -> Fragment1: position = 2
Fragment1 -> Fragment2: position = 3
Fragment2 -> Fragment3: position = 4
Fragment3 -> Fragment4: getItem is not called!
Fragment4 -> Fragment3: position = 2
Fragment3 -> Fragment2: position = 1
Fragment2 -> Fragment1: position = 0
Fragment1 -> Fragment0: getItem is not called!

Here is the code for my Adapter:

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class AppFragmentPageAdapter extends FragmentStatePagerAdapter {
    final int PAGE_COUNT = 5;
    private String tabTitles[] = new String[] { "اخبار", "حقیقت‌سنج", "ویدیوها", "زندگی‌نامه", "برنامه‌ها" };
    private Context context;

    public AppFragmentPageAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case (0):
                return NewsFragment.newInstance(position);
            default:
                return VideosFragment.newInstance(position);
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }
}

回答1:

It is normal behavior. By default FragmentStatePagerAdapter keep link for current displayed fragment and his neighbors. At first adapter create Fragment0 and Fragment1. When you swipe to Fragment1, he will create Fragment2 and call getItem(2) for this. After swipe to Fragment2, adapter will destroy Fragment0 and create Fragment3.