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)
OK, I think I've found a way to perform request b) in my own question so I'll share for others' benefit. The tag of fragments inside a ViewPager is in the form "android:switcher:VIEWPAGER_ID:INDEX"
, where VIEWPAGER_ID
is the R.id.viewpager
in XML layout, and INDEX is the position in the viewpager. So if the position is known (eg 0), I can perform in updateFragments()
:
HomeListFragment fragment =
(HomeListFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:"+R.id.viewpager+":0");
if(fragment != null) // could be null if not instantiated yet
{
if(fragment.getView() != null)
{
// no need to call if fragment's onDestroyView()
//has since been called.
fragment.updateDisplay(); // do what updates are required
}
}
I've no idea if this is a valid way of doing it, but it'll do until something better is suggested.