I\'m using a ViewPager
together with a FragmentStatePagerAdapter
to host three different fragments:
The main answer relies on a name being generated by the framework. If that ever changes, then it will no longer work.
What about this solution, overriding instantiateItem()
and destroyItem()
of your Fragment(State)PagerAdapter
:
public class MyPagerAdapter extends FragmentStatePagerAdapter {
SparseArray registeredFragments = new SparseArray();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return ...;
}
@Override
public Fragment getItem(int position) {
return MyFragment.newInstance(...);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
This seems to work for me when dealing with Fragments that are available. Fragments that have not yet been instantiated, will return null when calling getRegisteredFragment
. But I've been using this mostly to get the current Fragment
out of the ViewPager
: adapater.getRegisteredFragment(viewPager.getCurrentItem())
and this won't return null
.
I'm not aware of any other drawbacks of this solution. If there are any, I'd like to know.