When using the FragmentStatePageAdapter
I get the fragments like this:
@Override
public Fragment getItem(int position) {
return
Solution with storing fragments to a HashMap in your getItem() method does not work if your activity is re-created!
Problem is, default implementation of the FragmentStatePagerAdapter restores fragments directly from the FragmentManager without calling the getItem() method. This means that you'll never get a chance to store a reference to your fragment.
For more info, see source code: FragmentStatePagerAdapter#restoreState.
This basically means that the only way to get a reference to your fragment is by resorting to reflections. This is relatively* safe** in case youre using support library.
Here's how:
@SuppressWarnings("unchecked")
public Fragment getFragment(int position) {
try {
Field f = FragmentStatePagerAdapter.class.getDeclaredField("mFragments");
f.setAccessible(true);
ArrayList fragments = (ArrayList) f.get(this);
if (fragments.size() > position) {
return fragments.get(position);
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
relatively* means that its not as dangerous as using reflection on framework classes. Support classes are compiled into your app and there is no way that this code will work on your device but will crash on some other device. You can still potentially break this solution by updating support library to a newer version
safe** its never really safe to use reflections; however you have to resort to this method when a library you're using has design flaws.