我遇到了 FramentPageAdapter 的奇怪问题
MainActivity.java
@SuppressLint("ValidFragment")
public class MainActivity<DashboardActivity> extends FragmentActivity implements ActionBar.TabListener {
...
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(0)).setTabListener(this).setIcon(R.drawable.rating_good));
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(1)).setTabListener(this).setIcon(R.drawable.action_search));
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(2)).setTabListener(this).setIcon(R.drawable.action_search));
}
...
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position) {
case 0:
fragment = new Fragment0();
break;
case 1:
fragment = new Fragment1();
break;
case 2:
fragment = new Fragment2();
break;
}
return fragment;
}
@Override
public int getCount() {
return 3;
}
/*
* Title
*/
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section0).toUpperCase(l);
case 1:
return getString(R.string.title_section1).toUpperCase(l);
case 2:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
当我尝试在 3 个选项卡之间切换时,公共片段 getItem(int position) 返回错误的位置。当我创建只有 2 个选项卡的应用程序时,一切正常。添加超过 2 个,产生奇怪的问题。从 0 位置切换到 1 位置 - 工作正常,从 1 切换到 0 - 工作正常,从 1 位置切换到 2 位置 - 工作正常,但是,当我尝试从 2 位置返回到 1 位置时,公共片段 getItem(int position) - int 位置返回“0”而不是“1”。有人帮我吗?