Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 602
znat Avatar asked Apr 13 '12 15:04

znat


People also ask

How do you get ViewPager fragments?

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.

How do you call ViewPager fragment from activity?

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

How do I get fragments from Fragmentstateadapter?

If you have fragment tag though, you can easily retrieve reference to it from the FragmentManager by calling findFragmentByTag() .

How do I use pager adapter fragment?

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


1 Answers

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)

like image 142
CommonsWare Avatar answered Oct 05 '22 23:10

CommonsWare