The only documented way I found is:
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
But since the Fragment is instantiated in a ViewPager I don't have an id.
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
Thanks
ViewPager save Fragment in FragmentManager with particular tags, So We can get ViewPager's fragment by FragmentManager class by providing tag. And ViewPager provide tag to each fragment by following syntax : Fragment page = getSupportFragmentManager(). findFragmentByTag("android:switcher:" + R.
You'll just need to cast it to the real fragment class if you want to call a specific method. int pos = viewpager. getCurrentItem(); Fragment activeFragment = adapter. getItem(pos); if(pos == 0) ((NPListFragment)activeFragment).
If you have fragment tag though, you can easily retrieve reference to it from the FragmentManager by calling findFragmentByTag() .
When using FragmentPagerAdapter the host ViewPager must have a valid ID set. Subclasses only need to implement getItem and getCount to have a working adapter. super. onCreate(savedInstanceState);
You appear to be holding all fragments in memory in an oh-so-obsolete Vector
. In that case, you would retrieve your fragment out of that same Vector
. For example, call getCurrentItem()
on the ViewPager
to find the currently-selected fragment index, then call get()
on the Vector
with that index.
Note, though, that if you are relying on FragmentPagerAdapter
or FragmentStatePagerAdapter
to hold your fragments, that a fragment for a given index may not exist, either because it has not been created yet or it has been discarded to minimize memory consumption.
(BTW, see Why is Java Vector class considered obsolete or deprecated? for more on Vector
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With