Reputation: 1058
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
Upvotes: 7
Views: 9326
Reputation: 281
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.
Upvotes: 0
Reputation: 904
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 FragmentManager
s 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 :)
Upvotes: 1
Reputation: 3672
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.
Upvotes: 23