Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 806
Daniele B Avatar asked Feb 04 '14 05:02

Daniele B


1 Answers

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();
      }
  }
}
like image 191
Laimiux Avatar answered Oct 13 '22 19:10

Laimiux