问题描述
我正在使用 FragmentStatePagerAdapter
. getItem(int position)
返回错误的位置.我有5个片段.这是我更改片段时的位置:
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];
}
}
推荐答案
这是正常行为.默认情况下,FragmentStatePagerAdapter保留当前显示的片段及其邻居的链接.在第一个适配器上,创建Fragment0和Fragment1.当您滑动到Fragment1时,他将创建Fragment2并为此调用getItem(2).滑动到Fragment2后,适配器将销毁Fragment0并创建Fragment3.
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.
这篇关于FragmentStatePagerAdapter在getItem中返回错误位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!