How to make View.OnScrollChangeListener works on ViewPagger for android version 23 (Marshmallow) and below

1.2k views Asked by At

View.setOnScrollChangeListener is added in version 23. We want it works on below version as well. To do this, we can customize the scrollTo() function

1

There are 1 answers

0
THANN Phearum On

First, create your own listener which exactly get it from View.OnScrollChangeListener

public interface CustomOnScrollChangeListener {
    /**
     * Called when the scroll position of a view changes.
     *
     * @param v The view whose scroll position has changed.
     * @param scrollX Current horizontal scroll origin.
     * @param scrollY Current vertical scroll origin.
     * @param oldScrollX Previous horizontal scroll origin.
     * @param oldScrollY Previous vertical scroll origin.
     */
    void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
}

Then you can create a custom ViewPager class

public class CustomPager extends ViewPager {
    private int mScrollingX, mScrollingY;
    private CustomOnScrollChangeListener mListener;

    public CustomPager(Context context) {
        super(context);
    }

    public CustomPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setCustomScrollChangeListener(CustomOnScrollChangeListener listener) {
        mListener = listener;
    }

    @Override
    public void scrollTo(@Px int x, @Px int y) {
        super.scrollTo(x, y);
        if (mScrollingX != x || mScrollingY != y) {
            int oldX = mScrollingX;
            int oldY = mScrollingY;
            mScrollingX = x;
            mScrollingY = y;
            invalidate();
            mListener.onScrollChange(this, mScrollingX, mScrollingY, oldX, oldY);
            if (!awakenScrollBars()) {
                postInvalidateOnAnimation();
            }
        }
    }
}

And now you can start using it.

  mViewPager.setCustomScrollChangeListener(new CustomOnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX,
                    int oldScrollY) {
              //Put your logic code here
            }
        });