I have an FragmentActivity that has tabbed fragments using the example adapter set forth in FragmentTabsPager.java
(found in the Android Support v4 samples)
private static class TabsAdapter extends FragmentPagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
I have a menu entry in my FragmentActivity that will let me reload the data inside the fragments at will. Before I implemented the tab interface, I could guarantee that the needed fragment would be loaded in memory. I'd get the Fragment via getSupportFragmentManager().findFragmentById()
, cast it, then call its reload function. Simple enough.
Is there a way I can communicate with a specific Fragment instance loaded via FragmentPagerAdapter
from a FragmentActivity? Using TabAdapter
's getItem()
provided in the sample, I can retreive a new instance (via Fragment.instantiate()
) of my Fragment but not a reference to the one that's currently displayed. That's the one that matters.
EDIT: In addition to Plato's answer...
Since all my tabs are of different classes (eg. FooFragment, BarFragment, etc) it's very useful to identify and retrieve an active fragment of a specific type.
Object getActiveFragmentOfType(Class<?> cls) {
List<Fragment> frags = getActiveFragments();
for(Fragment one : frags) {
if(cls.isInstance(one)) {
return one;
}
}
return null;
}
Then when I want to work on a specific tab/fragment/class I just do something like this
Object fooFragmentObject = getActiveFragmentOfType(FooFragment.class);
if(fooFragmentObject != null) {
// Do something with an active reference to fooFragmentObject that's
// guaranteed to be castable to FooFragment
}