Getting the current Fragment instance in the viewpager

前端 未结 30 2628
醉话见心
醉话见心 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:11

    You can define the PagerAdapter like this then you will able to get any Fragment in ViewPager.

    private class PagerAdapter extends FragmentPagerAdapter {
        private final List mFragmentList = new ArrayList<>();
    
        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }
    
        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    
        public void addFragment(Fragment fragment) {
            mFragmentList.add(fragment);
        }
    }
    

    To get the current Fragment

    Fragment currentFragment = mPagerAdapter.getItem(mViewPager.getCurrentItem());
    

提交回复
热议问题