Getting the current Fragment instance in the viewpager

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

    This is more future-proof than the accepted answer:

    public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
    
        /* ------------------------------------------------------------------------------------------ */
        // region Private attributes :
    
        private Context _context;
        private FragmentManager _fragmentManager;
        private Map _fragmentsTags = new HashMap<>();
    
        // endregion
        /* ------------------------------------------------------------------------------------------ */
    
    
    
        /* ------------------------------------------------------------------------------------------ */
        // region Constructor :
    
        public MyFragmentPagerAdapter(Context context, FragmentManager fragmentManager) {
    
            super(fragmentManager);
    
            _context = context;
            _fragmentManager = fragmentManager;
        }
    
        // endregion
        /* ------------------------------------------------------------------------------------------ */
    
    
    
        /* ------------------------------------------------------------------------------------------ */
        // region FragmentPagerAdapter methods :
    
        @Override
        public int getCount() { return 2; }
    
        @Override
        public Fragment getItem(int position) {
    
            if(_fragmentsTags.containsKey(position)) {
    
                return _fragmentManager.findFragmentByTag(_fragmentsTags.get(position));
            }
            else {
    
                switch (position) {
    
                    case 0 : { return Fragment.instantiate(_context, Tab1Fragment.class.getName()); }
                    case 1 : { return Fragment.instantiate(_context, Tab2Fragment.class.getName()); }
                }
            }
    
            return null;
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
    
            // Instantiate the fragment and get its tag :
            Fragment result = (Fragment) super.instantiateItem(container, position);
            _fragmentsTags.put(position, result.getTag());
    
            return result;
        }
    
        // endregion
        /* ------------------------------------------------------------------------------------------ */
    }
    

提交回复
热议问题