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);
setOnPageChangeListener()
is now deprecated.addOnPageChangeListener()
should be used instead – Ocko