Getting the current Fragment instance in the viewpager Getting the current Fragment instance in the viewpager android android

Getting the current Fragment instance in the viewpager


by selecting an option, I need to update the fragment that is currently visible.

A simple way of doing this is using a trick related to the FragmentPagerAdapter implementation:

case R.id.addText:     Fragment page = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + ViewPager.getCurrentItem());     // based on the current position you can then cast the page to the correct      // class and call the method:     if (ViewPager.getCurrentItem() == 0 && page != null) {          ((FragmentClass1)page).updateList("new item");          } return true;

Please rethink your variable naming convention, using as the variable name the name of the class is very confusing(so no ViewPager ViewPager, use ViewPager mPager for example).


    public class MyPagerAdapter extends FragmentPagerAdapter {        private Fragment mCurrentFragment;        public Fragment getCurrentFragment() {            return mCurrentFragment;        }//...            @Override        public void setPrimaryItem(ViewGroup container, int position, Object object) {            if (getCurrentFragment() != object) {                mCurrentFragment = ((Fragment) object);            }            super.setPrimaryItem(container, position, object);        }    }


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.

@Overridepublic 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:

@Overridepublic 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!