Retrieve a Fragment from a ViewPager

前端 未结 23 2534
逝去的感伤
逝去的感伤 2020-11-21 11:13

I\'m using a ViewPager together with a FragmentStatePagerAdapter to host three different fragments:

  • [Fragment1]
  • [Fragment2]<
23条回答
  •  情话喂你
    2020-11-21 11:39

    FragmentPagerAdapter is the factory of the fragments. To find a fragment based on its position if still in memory use this:

    public Fragment findFragmentByPosition(int position) {
        FragmentPagerAdapter fragmentPagerAdapter = getFragmentPagerAdapter();
        return getSupportFragmentManager().findFragmentByTag(
                "android:switcher:" + getViewPager().getId() + ":"
                        + fragmentPagerAdapter.getItemId(position));
    }
    

    Sample code for v4 support api.

提交回复
热议问题