Getting the current Fragment instance in the viewpager

前端 未结 30 1941
醉话见心
醉话见心 2020-11-22 08:56

Below is my code which has 3 Fragment classes each embedded with each of the 3 tabs on ViewPager. I have a menu option. As shown in the onOpt

30条回答
  •  太阳男子
    2020-11-22 09:20

    To get current fragment - get position in ViewPager at public void onPageSelected(final int position), and then

    public PlaceholderFragment getFragmentByPosition(Integer pos){
        for(Fragment f:getChildFragmentManager().getFragments()){
            if(f.getId()==R.viewpager && f.getArguments().getInt("SECTNUM") - 1 == pos) {
                return (PlaceholderFragment) f;
            }
        }
        return null;
    }
    

    SECTNUM - position argument assigned in public static PlaceholderFragment newInstance(int sectionNumber); of Fragment

    getChildFragmentManager() or getFragmentManager() - depends on how created SectionsPagerAdapter

提交回复
热议问题