Retrieve a Fragment from a ViewPager

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

    The easiest and the most concise way. If all your fragments in ViewPager are of different classes you may retrieve and distinguish them as following:

    public class MyActivity extends Activity
    {
    
        @Override
        public void onAttachFragment(Fragment fragment) {
            super.onAttachFragment(fragment);
            if (fragment.getClass() == MyFragment.class) {
                mMyFragment = (MyFragment) fragment;
            }
        }
    
    }
    

提交回复
热议问题