Monday 24 June 2013

Get current visible fragment page in a ViewPager

There are two ways to get current visible fragment page in ViewPager.

FIRST APPROACH

You can set a unique tag on each fragment page like below

etSupportFragmentManager().beginTransaction().add(myFragment, "Some Tag").commit();

then retrieve the fragment page

getSupportFragmentManager().findFragmentByTag("Some Tag");

 You need to keep track of the string tags and link them with the fragments. Use a HashMap to store each tag along with the current page index, which is set at the time when the fragment page is instantiated.


MyFragment myFragment = MyFragment.newInstance();
mPageReferenceMap.put(index, "Some Tag");
getSupportFragmentManager().beginTransaction().add(myFragment, "Some Tag").commit();

To get current visible page's tag you need to call

int index = mViewPager.getCurrentItem();
String tag = mPageReferenceMap.get(index);

and then to get current visible fragment call

Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);


SECOND APPROACH

Second approach is also similar to the first one, here also we have to keep track of all the active fragments. In this case, you keep track of the fragments in the FragmentStatePagerAdapter.

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

You should not keep the reference of inactive fragments, to remove inactive fragments from mPageReferenceMap we need to implement FragmentStatePagerAdapter's destoryItem(...) method and do like below.

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

and to access the current visible fragment page, you then call


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

MyAdapter's getFragment(int) method should be like this

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

I prefer the second approach.