FragmentPagerAdapter - how to detect a swipe or a tab click when user goes to a new tab?

dowjones123 picture dowjones123 · Jan 17, 2015 · Viewed 25.3k times · Source

I have a MainActivity that has three fragments in a FragmentPagerAdapter as below. How can I find out when an user goes from 1st fragment to second or from second to third, either with swiping or with a click on the tab? I saw that the getItem() method is not called always as I have declared mViewPager.setOffscreenPageLimit(2);

public class MainThreeTabAdapter extends FragmentPagerAdapter {

    private final String[] CONTENT = new String[]{"News", "Rewards", "Me"};

    public MainThreeTabAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return NewsFragment.newInstance();
        } else if (position == 1) {
            return RewardsFragment.newInstance();
        } else if (position == 2) {
            return MeFragment.newInstance(true, App.getAccountData().getId());
        } else {
            return null;
        }

    }

    @Override
    public CharSequence getPageTitle(int position) {
        return CONTENT[position % CONTENT.length];
    }

    @Override
    public int getCount() {
        return CONTENT.length;
    }
}

In the MainActivity's onCreate()

    mainThreeTabAdapter = new MainThreeTabAdapter(getFragmentManager());

    // Set up the ViewPager with the sections adapter.
    // this ensures that 2 tabs on each side of current are kept in memory, which is all we need for our case. Default = 1
    // this is all taken from the Quickreturn facebook sample app
    mViewPager.setOffscreenPageLimit(2);
    mViewPager.setAdapter(mainThreeTabAdapter);

Answer

Andrew Orobator picture Andrew Orobator · Jan 17, 2015

The getItem() method is only called when creating a view. To understand why getItem() isn't being called, it helps to understand the default behavior of a ViewPager. By default, when you are on a particular page of a ViewPager it also creates the pages that are before and after this particular page. If you were to have 3 fragments named and in this order [a,b,c], and you were on page b, due to the default behavior of the ViewPager fragments a and c would already be created with a call to getItem(int). Because the fragments are already created, you won't get another call to getItem()

Aside: this behavior can be modified with ViewPager.setOffScreenLimit()

What you actually want to do in order to be notified when a user switches pages is to set a OnPageChangeListener to the ViewPager using ViewPager.addOnPageChangeListener() to be notified when a page is selected.