FragmentStatePagerAdapter在getItem中返回错误的位置

时间:2017-04-20 20:25:17

标签: android android-fragments fragmentmanager

我正在使用FragmentStatePagerAdaptergetItem(int position)返回错误的位置。我有5个片段。这是我改变片段时的位置:

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!

以下是我的适配器的代码:

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 个答案:

答案 0 :(得分:4)

这是正常行为。默认情况下,FragmentStatePagerAdapter保留当前显示的片段及其邻居的链接。首先,适配器创建Fragment0和Fragment1。当您滑动到Fragment1时,他将创建Fragment2并为此调用getItem(2)。滑动到Fragment2后,适配器将破坏Fragment0并创建Fragment3。