Update data in ListFragment as part of ViewPager

Barkside’s answer works with FragmentPagerAdapter but doesn’t work with FragmentStatePagerAdapter, because it doesn’t set tags on fragments it passes to FragmentManager.

With FragmentStatePagerAdapter it seems we can get by, using its instantiateItem(ViewGroup container, int position) call. It returns reference to fragment at position position. If FragmentStatePagerAdapter already holds reference to fragment in question, instantiateItem just returns reference to that fragment, and doesn’t call getItem() to instantiate it again.

So, suppose, I’m currently looking at fragment #50, and want to access fragment #49. Since they are close, there’s a good chance the #49 will be already instantiated. So,

ViewPager pager = findViewById(R.id.viewpager);
FragmentStatePagerAdapter a = (FragmentStatePagerAdapter) pager.getAdapter();
MyFragment f49 = (MyFragment) a.instantiateItem(pager, 49)

Leave a Comment