Retrieve a Fragment from a ViewPager

前端 未结 23 2544
逝去的感伤
逝去的感伤 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:38

    Add next methods to your FragmentPagerAdapter:

    public Fragment getActiveFragment(ViewPager container, int position) {
    String name = makeFragmentName(container.getId(), position);
    return  mFragmentManager.findFragmentByTag(name);
    }
    
    private static String makeFragmentName(int viewId, int index) {
        return "android:switcher:" + viewId + ":" + index;
    }
    

    getActiveFragment(0) has to work.

    Here is the solution implemented into ViewPager https://gist.github.com/jacek-marchwicki/d6320ba9a910c514424d. If something fail you will see good crash log.

提交回复
热议问题