由于没有找到嵌套FragmentActivity的方法,只好打算用不同的FragmentPagerAdapter来动态切换ViewPager的,如下:
/**
* 首页切换的三个界面
*/
private FragmentPagerAdapter mPagerAdapter1 = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem( final int position) {
switch (position) {
case 1:
return new Fragment1();
case 2:
return new Fragment2();
default:
return new Fragment3();
}
}
@Override
public int getCount() {
return 3;
}
};
private FragmentPagerAdapter mPagerAdapter2 = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem( final int position) {
switch (position) {
case 1:
return new Fragment4();
case 2:
return new Fragment5();
default:
return new Fragment6();
}
}
@Override
public int getCount() {
return 3;
}
};
* 首页切换的三个界面
*/
private FragmentPagerAdapter mPagerAdapter1 = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem( final int position) {
switch (position) {
case 1:
return new Fragment1();
case 2:
return new Fragment2();
default:
return new Fragment3();
}
}
@Override
public int getCount() {
return 3;
}
};
private FragmentPagerAdapter mPagerAdapter2 = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem( final int position) {
switch (position) {
case 1:
return new Fragment4();
case 2:
return new Fragment5();
default:
return new Fragment6();
}
}
@Override
public int getCount() {
return 3;
}
};
然后很自然的想用ViewPager的setAdapter动态设置来切换, 结果发现不起作用!!莫有办法,只好先把Fragment清理一下,如下:
public
void switchViewPages(FragmentPagerAdapter mAdapter,
int[] tabs) {
if (mViewPager.getAdapter() != null) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Bundle bundle = new Bundle();
int index = mViewPager.getAdapter().getCount();
String key = "index";
while (index >= 0) {
bundle.putInt(key, index);
ft.remove(fm.getFragment(bundle, key));
index--;
}
ft.commit();
}
mViewPager.setAdapter(mAdapter);
if (mViewPager.getAdapter() != null) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Bundle bundle = new Bundle();
int index = mViewPager.getAdapter().getCount();
String key = "index";
while (index >= 0) {
bundle.putInt(key, index);
ft.remove(fm.getFragment(bundle, key));
index--;
}
ft.commit();
}
mViewPager.setAdapter(mAdapter);
查看了一下FragmentManager的源码,学会了getFragmen的用法,这个方法方便通过索引取Fragment。
本文转自博客园农民伯伯的博客,原文链接:【Andorid X 项目笔记】动态设置ViewPager的Adapter问题(2),如需转载请自行联系原博主。