Retrieve a Fragment from a ViewPager

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

    Must extends FragmentPagerAdapter into your ViewPager adapter class.
    If you use FragmentStatePagerAdapter then you will not able to find your Fragment by its ID

    public static String makeFragmentName(int viewPagerId, int index) {
      return "android:switcher:" + viewPagerId + ":" + index;
    }
    

    How to use this method :-

    Fragment mFragment = ((FragmentActivity) getContext()).getSupportFragmentManager().findFragmentByTag(
           AppMethodUtils.makeFragmentName(mViewPager.getId(), i)
    );
    InterestViewFragment newFragment = (InterestViewFragment) mFragment;
    

提交回复
热议问题