如何使View.OnScrollChangeListener适用于Android版本23(Marshmallow)及以下版本的ViewPagger

时间:2017-08-01 02:24:24

标签: android android-viewpager android-6.0-marshmallow onscrollchanged

版本23中添加了

View.setOnScrollChangeListener。 我们希望它也适用于以下版本。 为此,我们可以自定义scrollTo()函数

1 个答案:

答案 0 :(得分:0)

首先,创建一个自己的监听器,从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);
}

然后您可以创建自定义ViewPager

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();
            }
        }
    }
}

现在你可以开始使用它了。

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