Skip to content

Instantly share code, notes, and snippets.

@brendanw
Created February 19, 2016 23:32
Show Gist options
  • Save brendanw/e79d0ad972fb715e96c5 to your computer and use it in GitHub Desktop.
Save brendanw/e79d0ad972fb715e96c5 to your computer and use it in GitHub Desktop.
Detect when a ViewPager smoothScroll initialized by viewPager.setCurrentItem() has completed
import android.support.v4.view.ViewPager;
import android.view.ViewTreeObserver;
/**
* A class that can be added to a viewTreeObserver for ViewPager's in order to determine
* when a smoothScroll transition is completed by viewPager.setCurrentItem();
*/
public class PagerScrollListener implements ViewTreeObserver.OnScrollChangedListener {
private int scrollX;
private int totalChange = 0;
private OnTransitionCompleteListener onTransitionCompleteListener;
private ViewPager viewPager;
public PagerScrollListener(OnTransitionCompleteListener onTransitionCompleteListener, ViewPager viewPager) {
this.scrollX = viewPager.getScrollX();
this.onTransitionCompleteListener = onTransitionCompleteListener;
this.viewPager = viewPager;
}
@Override
public void onScrollChanged() {
totalChange += Math.abs(scrollX - viewPager.getScrollX());
scrollX = viewPager.getScrollX();
if(totalChange == viewPager.getWidth()) {
viewPager.getViewTreeObserver().removeOnScrollChangedListener(this);
onTransitionCompleteListener.onTransitionComplete();
}
}
public interface OnTransitionCompleteListener {
void onTransitionComplete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment