I have following problem: I have one activity in which I have two tabs which are made both as fragments using FragmentPagerAdapter In some moment I would l
I found a slightly less gross way to get a handle on a Fragment
created by a FragmentPagerAdapter
.
Instead of imitating the way tags are created, override instantiateItem()
, get the Fragment
returned by the superclass, and save the tag in TabInfo
. This works for me on API >= 15, may work with lower. This still makes some assumptions about private code.
static final class TabInfo {
private final Class> clss;
private final Bundle args;
private String tag; // ** add this
TabInfo(Class> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
final Fragment fragment = (Fragment) super.instantiateItem(container, position);
final TabInfo info = mTabs.get(position);
info.tag = fragment.getTag(); // set it here
return fragment;
}
Or in API < 16, I think instantiateItem()
takes a View()
instead of ViewGroup()
, like this:
public Object instantiateItem(View container, int position);
Then allow a way to get the Fragment
, keeping the hack contained.
public Fragment getFragment(int index) {
return mContext.getFragmentManager().findFragmentByTag(mTabs.get(index).tag);
}
For that to work, the declaration for mContext
needs to change to Activity
, it's passed in as an Activity
anyway:
private final Activity mContext;