1

Short version:

I have activity with fragment, which include ViewPager (with FragmentStatePagerAdapter) and on resume to this fragment it recreates. How can I by back press return to Fragment and restore is state and it's Viewpager?

Details:

I have an activity with FrameLayout (R.id.themesFragmentsLayout), in activity's method onCreate(..) I do:

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 include only ViewPager with FragmentStatePagerAdapter, which holds 3 fragments:

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;
    }
}

In ThemeOfDayFragment for example, user can click some button and I change ThemesFragment (which holds ViewPager) with some another (for example 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

But when he came back (by back key press for example) ThemesFragment recreates, and all fragments in ViewPager recreates to. In ThemesFragment I set setRetainInstance(true)

Can anyone help?

Ben Weiss
  • 17,182
  • 6
  • 67
  • 87
edredos
  • 11
  • 3

0 Answers0