I\'m using a ViewPager
together with a FragmentStatePagerAdapter
to host three different fragments:
I know this has a few answers, but maybe this will help someone. I have used a relatively simple solution when I needed to get a Fragment
from my ViewPager
. In your Activity
or Fragment
holding the ViewPager
, you can use this code to cycle through every Fragment
it holds.
FragmentPagerAdapter fragmentPagerAdapter = (FragmentPagerAdapter) mViewPager.getAdapter();
for(int i = 0; i < fragmentPagerAdapter.getCount(); i++) {
Fragment viewPagerFragment = fragmentPagerAdapter.getItem(i);
if(viewPagerFragment != null) {
// Do something with your Fragment
// Check viewPagerFragment.isResumed() if you intend on interacting with any views.
}
}
If you know the position of your Fragment
in the ViewPager
, you can just call getItem(knownPosition)
.
If you don't know the position of your Fragment
in the ViewPager
, you can have your children Fragments
implement an interface with a method like getUniqueId()
, and use that to differentiate them. Or you can cycle through all Fragments
and check the class type, such as if(viewPagerFragment instanceof FragmentClassYouWant)
!!! EDIT !!!
I have discovered that getItem
only gets called by a FragmentPagerAdapter
when each Fragment
needs to be created the first time, after that, it appears the the Fragments
are recycled using the FragmentManager
. This way, many implementations of FragmentPagerAdapter
create new Fragment
s in getItem
. Using my above method, this means we will create new Fragment
s each time getItem
is called as we go through all the items in the FragmentPagerAdapter
. Due to this, I have found a better approach, using the FragmentManager
to get each Fragment
instead (using the accepted answer). This is a more complete solution, and has been working well for me.
FragmentPagerAdapter fragmentPagerAdapter = (FragmentPagerAdapter) mViewPager.getAdapter();
for(int i = 0; i < fragmentPagerAdapter.getCount(); i++) {
String name = makeFragmentName(mViewPager.getId(), i);
Fragment viewPagerFragment = getChildFragmentManager().findFragmentByTag(name);
// OR Fragment viewPagerFragment = getFragmentManager().findFragmentByTag(name);
if(viewPagerFragment != null) {
// Do something with your Fragment
if (viewPagerFragment.isResumed()) {
// Interact with any views/data that must be alive
}
else {
// Flag something for update later, when this viewPagerFragment
// returns to onResume
}
}
}
And you will need this method.
private static String makeFragmentName(int viewId, int position) {
return "android:switcher:" + viewId + ":" + position;
}