1

精简版:

我有片段活动,其中包括 ViewPager(使用 FragmentStatePagerAdapter),并在恢复到该片段时重新创建。如何通过后按返回 Fragment 并恢复状态和 Viewpager?

细节:

我有一个带有 FrameLayout (R.id.themesFragmentsLayout) 的活动,在活动的 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 仅包含 ViewPager 和 FragmentStatePagerAdapter,它包含 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)

任何人都可以帮忙吗?

4

0 回答 0