Search code examples
androidandroid-fragmentsandroid-fragmentactivityfragmentstatepageradapter

FragmentStatePagerAdapter fails to load the fragments again when I get back to old instance of the parent Fragment


Scenario:

I have a fragment which has a ViewPager which contains 5 instances(different) of a single Fragment with different values, each having a listivew that contains some sort of items.

Problem:

The flow goes smooth when I click an item of listView(say on page1) but the moment I come back from there on pressing back (overridden OnBackPressed in the main_activity (will discuss later)), the viewPager fails to load the subFragments.

But when I switch to the 2nd or 3rd page, it gets displayed, and on going back to 1st page, it now gets displayed.

OnBackPressed():

I am maintaining a manual stack here. When I click on an item of ListView, the current Fragment Instance (of the parent Fragment ofcourse) goes into stack. And when user comes back , that instance gets popped off the stack and I replaces it on the activities FrameLayout container.

References:

Fragments not getting recreated by FragmentStatePagerAdapter after coming back to the main Fragment instance

Guys, I am really pissed off here, please help me out.


Solution

  • Finally I am able to get a workaround for this issue, which included two things:

    1. while replacing the fragment make a call to

      ft.replace(R.id.content_frame, frag).addToBackStack(null);
      
    2. while initiating the ViewPager, the fragment manager to be used is :

      mAdapter = new myAdapter(getChildFragmentManager());

    Actually the problem is that, android fails to recognise and load the older instance of the fragment unless you explicitly add that instance to the backstack. So after adding it to BackStack, there is practically no need to maintain your own manual Stack, but you still can do that.