ViewPager is not always updated when setAdapter, FragmentStatePagerAdapter is called

First of all, I use the FragmentStatePagerAdapter to feed the ViewPager with the displayed fragments.

When the application is in working condition (i.e. after onResume() ), calling setAdapter on the ViewPager will always work and update the ViewPager, the getItem(int position) method in the adapter is called.

However, after changing the orientation, 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 think maybe the FragmentManager is doing what I don't understand? The fragment manager is the only thing that does not collapse during orientation changes.

thanks

+7
source share
3 answers

This may be because you are using getFragmentManager() to instantiate the FragmentStatePagerAdapter using nested fragments.

Try using getChildFragmentManager() instead:

 CustomFragmentPagerAdapter fragmentPagerAdapter = new CustomFragmentPagerAdapter(getChildFragmentManager()); 

The answer was found here .

+21
source

Well, that’s what I found out (this is very strange).

If you need to update elements in the PagerAdapter , you probably will not be able to do this by creating new instances of PageAdapter when you pass the same FragmentManager and pass them to the setAdapter call to the ViewPager , for example:

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

or

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

But if you keep switching the FragmentManager when you initialize the PagerAdapter , then it will work.

From my point of view, this is terrible ... If someone has ideas on how to correctly edit elements in ViewPager (and not in this dirty form), share your thoughts with others :)

+1
source

I am using FragmentPagerAdapter, and mViewPager.setAdapter () is not working. I will fix it in the next step:
(1) get the current list of fragments.

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

(2) remove the fragment in mom's

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

(3) set the new FragmentPagerAdapter to the ViewPager

 mViewPager.setAdapter(...) 

Just remove fragments before installing a new adapter.

0
source

All Articles