Android: PagerAdapter's setPrimaryItem() being called more than once

android, android-viewpager

Solution

Yes, for me it even kept calling infinitely. However, if you need something to be called once, here is a simple solution

public class MyPagerAdapter extends PagerAdapter {
    private int lastPosition = -1;

    @Override public void setPrimaryItem(ViewGroup container, int position, Object object) {
      super.setPrimaryItem(container, position, object);

      // Only refresh when primary changes
      if(lastPosition != position) {
        lastPosition = position;

        yourFunction();
      }
  }
}

Problem

Why is `PagerAdapter.setPrimaryItem()` called more than once (with the same values) after I select a new page with `ViewPager.setCurrentItem(index)` ?

Original source