How can I get a reference to a Fragment in a ViewPager?

android, android-fragments

Solution

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`)

Problem

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

Original source

Related problems