Getting the current Fragment instance in the viewpager

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

    First of all keep track of all the "active" fragment pages. In this case, you keep track of the fragment pages in the FragmentStatePagerAdapter, which is used by the ViewPager.

    @Override
    public Fragment getItem(int index) {
        Fragment myFragment = MyFragment.newInstance();
        mPageReferenceMap.put(index, myFragment);
        return myFragment;
    }
    

    To avoid keeping a reference to "inactive" fragment pages, you need to implement the FragmentStatePagerAdapter's destroyItem(...) method:

    @Override
    public void destroyItem (ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
        mPageReferenceMap.remove(position);
    }
    

    and when you need to access the currently visible page, you then call:

    int index = mViewPager.getCurrentItem();
    MyAdapter adapter = ((MyAdapter)mViewPager.getAdapter());
    MyFragment fragment = adapter.getFragment(index);
    

    Where the MyAdapter's getFragment(int) method looks like this:

    public MyFragment getFragment(int key) {
        return mPageReferenceMap.get(key);
    }
    

    Hope it may help!

提交回复
热议问题