Retrieve a Fragment from a ViewPager

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

    Another simple solution:

        public class MyPagerAdapter extends FragmentPagerAdapter {
            private Fragment mCurrentFragment;
    
            public Fragment getCurrentFragment() {
                return mCurrentFragment;
            }
    //...    
            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                if (getCurrentFragment() != object) {
                    mCurrentFragment = ((Fragment) object);
                }
                super.setPrimaryItem(container, position, object);
            }
        }
    

提交回复
热议问题