Retrieve a Fragment from a ViewPager

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

    This is based on Steven's answer above. This will return actual instance of the fragment which is already attached to the parent activity.

    FragmentPagerAdapter fragmentPagerAdapter = (FragmentPagerAdapter) mViewPager.getAdapter();
        for(int i = 0; i < fragmentPagerAdapter.getCount(); i++) {
    
            Fragment viewPagerFragment = (Fragment) mViewPager.getAdapter().instantiateItem(mViewPager, i);
            if(viewPagerFragment != null && viewPagerFragment.isAdded()) {
    
                if (viewPagerFragment instanceof FragmentOne){
                    FragmentOne oneFragment = (FragmentOne) viewPagerFragment;
                    if (oneFragment != null){
                        oneFragment.update(); // your custom method
                    }
                } else if (viewPagerFragment instanceof FragmentTwo){
                    FragmentTwo twoFragment = (FragmentTwo) viewPagerFragment;
    
                    if (twoFragment != null){
                        twoFragment.update(); // your custom method
                    }
                }
            }
        }
    

提交回复
热议问题