Retrieve a Fragment from a ViewPager

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

    The main answer relies on a name being generated by the framework. If that ever changes, then it will no longer work.

    What about this solution, overriding instantiateItem() and destroyItem() of your Fragment(State)PagerAdapter:

    public class MyPagerAdapter extends FragmentStatePagerAdapter {
        SparseArray registeredFragments = new SparseArray();
    
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public int getCount() {
            return ...;
        }
    
        @Override
        public Fragment getItem(int position) {
            return MyFragment.newInstance(...); 
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = (Fragment) super.instantiateItem(container, position);
            registeredFragments.put(position, fragment);
            return fragment;
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            registeredFragments.remove(position);
            super.destroyItem(container, position, object);
        }
    
        public Fragment getRegisteredFragment(int position) {
            return registeredFragments.get(position);
        }
    }
    

    This seems to work for me when dealing with Fragments that are available. Fragments that have not yet been instantiated, will return null when calling getRegisteredFragment. But I've been using this mostly to get the current Fragment out of the ViewPager: adapater.getRegisteredFragment(viewPager.getCurrentItem()) and this won't return null.

    I'm not aware of any other drawbacks of this solution. If there are any, I'd like to know.

提交回复
热议问题