Sometimes we need to know when fragment is selected and to handle it.
1. Add interface:
public interface FragmentSelection{ void onPageUnSelected(); void onPageSelected(); }
2. Implement this interface in your fragments:
public class YourFragment extends Fragment implements SetScrollingActivity.FragmentSelection { ... @Override public void onPageUnSelected() { // } @Override public void onPageSelected() { // }
3. Add ‘setOnPageChangeListener’ on yours ViewPager instance
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int newPosition) { FragmentSelection fragmentToShow = (FragmentSelection) mSetScrollingAdapter.instantiateItem(mViewPager, newPosition); fragmentToShow.onPageSelected(); FragmentSelection fragmentToHide = (FragmentSelection) mSetScrollingAdapter.instantiateItem(mViewPager, currentPosition); fragmentToHide.onPageUnSelected(); currentPosition = newPosition; } @Override public void onPageScrollStateChanged(int state) { } });