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
A simpler approach to this is to get the Tags directly from the Fragment Manager; like this:
fm.getFragments().get(0).getTag()
You can replace the position, depending on the fragment you need the tag for. Hope this helps others!.
It is very late to answer this question but i have searched a lot no one tell me the exact answer, Might be some one found it useful.
I have set my fragments through FragmentPagerAdapter
and i did communication between fragments
https://developer.android.com/training/basics/fragments/communicating.html#Deliver
following this link and for FindFragmentById i simply used viewpager.getId() on the mainactivity .
The Fragments supplied by the FragmentPagerAdapter are auto-tagged when they're instantiated. You can retrieve the tag with this method:
private static String makeFragmentName(int viewPagerId, int index) {
return "android:switcher:" + viewPagerId + ":" + index;
}
Reference: reusing fragments in a fragmentpageradapter
With this function you can find the fragment by pager adapter position.
public Fragment findFragmentByPosition(int position) {
FragmentPagerAdapter fragmentPagerAdapter = getFragmentPagerAdapter();
return getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + getViewPager().getId() + ":"
+ fragmentPagerAdapter.getItemId(position));
}
Sample code for v4 support api.
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;