MyFragment currentFragment = (MyFragment) getSupportFragmentManager()
.findFragmentByTag("f"+pagerMainAdapter.getItemId(0));
currentFragment.testRun("Hello world");
I'm trying to Migrate from ViewPager to ViewPager2 and and I don't know how to get fragment in ViewPager2.
To get the current fragment from ViewPager2:
The
ViewPager2hasgetCurrentItem()which returns the current page number So, we need to link each page fragment to the corresponding page number.But we can get a
ViewPager2fragment by its id (item id), so the first step is to have page Ids that equals to the corresponding position, to do so overridegetItemIdin theViewPager2FragmentStateAdapter.Then to get the current fragment:
EDIT:
Apart from the question, getting the
viewPagerfragment using"f$id"can be discontinued some day by Google in internal APIs; so you should use another way for that; here is a one that can be used in API 24+:Using
newInstancepage fragment pattern, you can set some argument in theviewPagerpage fragment, assumingviewPagerfragment isPagerFragment:Argument constant:
Adapter:
PageFragment:
And to get a fragment of a certain
viewPageritem: