简短版本:
我有片段的活动,其中包括ViewPager(带有FragmentStatePagerAdapter),并且在重新创建时会重新创建此片段。我怎样才能通过反压返回Fragment并恢复状态,它是Viewpager?
详细说明:
我在FrameLayout(R.id.themesFragmentsLayout)中有一个活动,在activity的方法onCreate(..)我这样做:
if (savedInstanceState == null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ThemesFragment fragment = new ThemesFragment();
fragmentTransaction.replace(R.id.themesFragmentsLayout, fragment, ThemesFragment.TAG);
fragmentTransaction.commit();
}
ThemesFragment仅包含带有FragmentStatePagerAdapter的ViewPager,它包含3个片段:
public Fragment getItem(int position) {
switch (position) {
case ID_THEME_PAST:
return new ThemePastFragment();
case ID_THEME_OF_DAY:
return new ThemeOfDayFragment();
case ID_THEME_UPCOMING:
return new ThemeUpcomingFragment();
default:
return null;
}
}
例如,在ThemeOfDayFragment中,用户可以单击某个按钮,然后将ThemesFragment(包含ViewPager)更改为另一个(例如ThemeDetails):
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.addToBackStack(newFragment.getClass().getSimpleName());
fragmentTransaction.replace(((AboutMyStyleApplication) getActivity().getApplication()).getCurrentFragmentsLayoutId(), newFragment, newFragment.getClass().getSimpleName());
fragmentTransaction.commitAllowingStateLoss(); // or fragmentTransaction.commit(); - same result
但当他回来时(例如通过后退按键),ThemesFragment会重新创建,并且ViewPager中的所有片段都会重新创建。 在ThemesFragment中我设置了setRetainInstance(true)
有人可以帮忙吗?