Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager doesn't always refresh when setAdapter is called, FragmentStatePagerAdapter

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

like image 676
Chao Avatar asked Nov 26 '12 00:11

Chao


People also ask

How do I notify ViewPager?

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.

How do I refresh FragmentPagerAdapter?

You can use startActivityForResult(or broadcast/receiver) to get the result from the activity. Then use adapter. notifyDataSetChanged to refresh the fragment.

Is ViewPager deprecated?

Technically, ViewPager is not deprecated, but the two concrete PagerAdapter implementations — FragmentPagerAdapter and FragmentStatePagerAdapter — are deprecated.


2 Answers

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.

like image 67
fahmy Avatar answered Jun 08 '23 07:06

fahmy


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 :)

like image 23
Toochka Avatar answered Jun 08 '23 09:06

Toochka