我是在我的单一 Activity 应用程序中使用嵌套的 FragmentStatePagerAdapter。当前布局为:
Activitiy
- Login Fragment
- Master Fragment
- Tab Fragment #1
- Tab Fragment #2
- Tab Fragment #3
- Another Fragment
- Another Fragment
每次我从“另一个片段”切换回“主片段”,例如 FragmentStatePagerAdapter 会多次实例化相同的项。
第一次:选项卡片段#1 #2 #3
第二次:选项卡片段#1 #1 #2 #2 #3 #3
第三次:选项卡片段#1 #1 #1 #2 #2 #2 #3 #3 #3。
我使用以下代码在片段之间移动:
getSupportFragmentManager()
.beginTransaction()
.replace(android.R.id.content, XXXX.newInstance(query), TAG_XXX)
.addToBackStack(null)
.commit();
主碎片代码:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initFragmentAdapter();
}
private void initFragmentAdapter() {
final FragmentSimpleAdapter adapter = new FragmentSimpleAdapter(getChildFragmentManager());
adapter.addFragment(
getString(...),
"...",
XXX.class);
...
ViewPager viewPager = (ViewPager) getActivity().findViewById(android.R.id.tabcontent);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(4);
PagerSlidingTabStrip viewTabs = (PagerSlidingTabStrip) getActivity().findViewById(
android.R.id.tabhost);
viewTabs.setViewPager(viewPager);
viewTabs.setOnPageChangeListener(adapter);
}
private final class FragmentSimpleAdapter extends FragmentStatePagerAdapter
implements ViewPager.OnPageChangeListener {
private final List<String> mTitles = new LinkedList<>();
private final List<String> mInstances = new LinkedList<>();
private final List<String> mTag = new LinkedList<>();
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
public FragmentSimpleAdapter(FragmentManager fm) {
super(fm);
mFragmentManager = fm;
mFragmentTags = new HashMap<>();
}
@Override
public int getCount() {
return mTitles.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mTitles.get(position);
}
@Override
public Fragment getItem(int position) {
return Fragment.instantiate(getActivity(), mInstances.get(position), null);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment) {
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
}
return obj;
}
public Fragment getFragment(int position) {
String tag = mFragmentTags.get(position);
if (tag == null) {
return null;
}
return mFragmentManager.findFragmentByTag(tag);
}
public FragmentSimpleAdapter addFragment(String title, String tag,
Class<? extends Fragment> fragment) {
mTitles.add(title);
mTag.add(tag);
mInstances.add(fragment.getName());
return this;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Analytics.sendViewAnalytic(mTag.get(position))
}
@Override
public void onPageScrollStateChanged(int state) {
}
}