How to get a fragment in FragmentStateAdapter

Solution for How to get a fragment in FragmentStateAdapter
is Given Below:

MyFragment currentFragment = (MyFragment) getSupportFragmentManager()
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 ViewPager2 has getCurrentItem() which returns the current page number
So, we need to link each page fragment to the corresponding page number.

But we can get a ViewPager2 fragment by its id (item id), so the first step is to have page Ids that equals to the corresponding position, to do so override getItemId in the ViewPager2 FragmentStateAdapter.

public long getItemId(int position) {
    return position;

Then to get the current fragment:

int pageId = viewpager.getCurrentItem();

MyFragment currentFragment = (MyFragment) getSupportFragmentManager()
                                              .findFragmentByTag("f" + pageId);