How can I get a link to a fragment in ViewPager?

The only documented way I found is:

MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment); 

But since the Fragment is being created in the ViewPager, I don't have an identifier.

  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

+6
source share
1 answer

It seems that you keep all the fragments in memory in oh-so-deprecated Vector . In this case, you will extract a fragment from the same Vector . For example, call getCurrentItem() in the ViewPager to find the currently selected fragment, then call get() on Vector with this index.

Note that if you rely on the FragmentPagerAdapter or FragmentStatePagerAdapter to store your slices, the snippet for this index may not exist because it has not been created yet or it has been discarded to minimize memory consumption.

(BTW, see Why is the Java Vector class considered obsolete or deprecated? More for Vector )

+5
source

Source: https://habr.com/ru/post/913140/


All Articles