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
The notifyDataSetChanged() method on the PagerAdapter will only notify the ViewPager that the underlying pages have changed. For example, if you have created/deleted pages dynamically (adding or removing items from your list) the ViewPager should take care of that.
You can use startActivityForResult(or broadcast/receiver) to get the result from the activity. Then use adapter. notifyDataSetChanged to refresh the fragment.
Technically, ViewPager is not deprecated, but the two concrete PagerAdapter implementations — FragmentPagerAdapter and FragmentStatePagerAdapter — are deprecated.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With