声明
欢迎转载,但请保留文章原始出处:)
博客园:http://www.cnblogs.com
农民伯伯: http://over140.cnblogs.com
正文
由于没有找到嵌套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; } };
然后很自然的想用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);
查看了一下FragmentManager的源码,学会了getFragmen的用法,这个方法方便通过索引取Fragment。