android 监听scrollview 滑动动作

来源:互联网 发布:诈骗罪立案后网络追逃 编辑:程序博客网 时间:2024/06/05 07:22

自定义控件,实现监听scrollview的上滑,下滑,滑到底部,滑到顶部。


具体看代码:


public class MyScrollView extends ScrollView{    private ScrollToListener mScrollToListener;    private int mScrolledDistance = 0;    private View contentView;    public static final int SLIDER = 200;    public MyScrollView(Context context) {        super(context);        init();    }    public MyScrollView(Context context, AttributeSet attrs) {        super(context, attrs);        init();    }    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    private void init(){        this.setOnScrollChangeListener(new OnScrollChangeListener() {            @Override            public void onScrollChange(View view, int i, int i1, int i2, int i3) {                int dy = i1 - i3;                if (mScrolledDistance > SLIDER) {                    mScrollToListener.toUp();                    mScrolledDistance = 0;                } else if (mScrolledDistance < -SLIDER) {                    mScrollToListener.toDown();                    mScrolledDistance = 0;                }                if ((dy > 0) || (dy < 0)) {                    mScrolledDistance += dy;                }                doToBottomListener();            }        });    }    private void doToBottomListener() {        if (contentView != null && contentView.getMeasuredHeight() <= getScrollY() + getHeight()) {            if (mScrollToListener != null) {                mScrollToListener.toBottom();            }        } else if (getScrollY() == 0) {            if (mScrollToListener != null) {                mScrollToListener.toTop();            }        }    }    public void setScrollToListener(ScrollToListener listener){        mScrollToListener = listener;        if (contentView == null) {            contentView = getChildAt(0);        }    }    public interface ScrollToListener{        void toUp();        void toDown();        void toTop();        void toBottom();    }}

0 0
原创粉丝点击