Problem
I was looking over the solution to this SO post from a while back. This solution makes sense to me. However, I'm having issues as to when I should try accessing the fragment that is currently being displayed. I'm using the same setup as the linked question: a ViewPager
with a FragmentStatePagerAdapter
. I've implemented the adjustments to my FragmentStatePagerAdapter
as the solution suggests:
private class MyPagerAdapter extends FragmentStatePagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
}
@Override
public Fragment getItem(int position) {
mCursor.moveToPosition(position);
return ArticleDetailFragment.newInstance(mCursor.getLong(ArticleLoader.Query._ID));
}
@Override
public int getCount() {
return (mCursor != null) ? mCursor.getCount() : 0;
}
@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);
}
}
The issue comes when trying to access the current fragment. I tried accessing it within onResume()
:
@Override
protected void onResume() {
super.onResume();
ArticleDetailFragment fragment = (ArticleDetailFragment)
mPagerAdapter.getRegisteredFragment(mPager.getCurrentItem());
mCallback = (FragmentCallback) fragment;
}
...But my fragment is always null. This is because onResume()
is called prior to instantiateItem()
is called within my adapter. The fragment is null because no fragments have been added yet to registeredFragments
within the adapter.
Question
I was hoping to get some guidance on which activity lifecycle method I should use where instantiateItems()
would have already been called and I'd have actual fragments to work with. As always, any help on this would be appreciated.
Additional Background
What I'm really trying to achieve with this is to get a reference to my fragment so that I can instantiate a callback interface that I've defined in my activity. I'm hoping to use this interface to communicate with the fragment that's currently being displayed within the ViewPager
. However, in order to be able to do that, I first need a reference to the current fragment.