7
votes

First of all, I am using FragmentStatePagerAdapter to feed a ViewPager with fragments to display.

When app is in the running state (i.e. after onResume()), calling setAdapter on the ViewPager will always work and make my ViewPager refresh, the getItem(int position) method in the adapter is called.

However after an orientation change, if I call setAdapter in the onCreate(Bundle savedInstance) method of my activity, the getItem(int position) method is not called, and the old fragment is reused.

I am thinking maybe the FragmentManager is doing something that I don't understand? The Fragment Manager is the only thing that doesn't get destroyed during the orientation change.

Thanks

3
The problem is the SavedState. I have the same problem but no solution. You can try following: befor you set the adapter call adapter.saveState, than set the adapter and call restoreSavedState with the saved state. In my case it didn't help, but maybe for you. Reason: in the ViewPager setAdapter it saved the current state and reused it. (i think)Informatic0re
Does this cause memory leaks ? Many say it does. Any other solution how to handle this scenario ?pradyumnad
awesome, thanks for the reply. finally solved it..pradyumnad

3 Answers

23
votes

It could be because you are using getFragmentManager() to instantiate the FragmentStatePagerAdapter while using nested fragments.

Try using getChildFragmentManager() instead:

CustomFragmentPagerAdapter fragmentPagerAdapter = new CustomFragmentPagerAdapter(getChildFragmentManager());

Answer was found here.

1
votes

Well here is the thing that I found out (it's very very odd).

If you need to refresh items in PagerAdapter you will most certainly fail to do so creating new instances of PageAdapter when you do pass the same FragmentManager and passing them to the setAdapter call of ViewPager, e.g.:

FragmentManager fm = getChildFragmentManager();
mViewPager.setAdapter(new MyPagerAdapter(fm));

or

FragmentManager fm = getActivity().getSupportFragmentManager();
mViewPager.setAdapter(new MyPagerAdapter(fm));

But if you'll constantly switch FragmentManagers when you're initialising PagerAdapter then it'll work.

From my point of view it's horrible... If anyone has ideas of how to refresh items in ViewPager properly (and not in this dirty way), share your thoughts with others :)

0
votes

I use the FragmentPagerAdapter and mViewPager.setAdapter() is not work.I fix it in the below step:
(1)get the current Fragment list.

List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
List<Fragment> fragmentListCopy = new ArrayList<Fragment>(fragmentList);

(2)remove fragment mamually

//I have two fragment
getSupportFragmentManager().beginTransaction().remove(fragmentList.get(0)).commit();
getSupportFragmentManager().beginTransaction().remove(fragmentList.get(1)).commit();

(3)set new FragmentPagerAdapter to ViewPager

mViewPager.setAdapter(...)

Just remove the fragments before you set new Adapter.