其他分享
首页 > 其他分享> > Android:ScrollView停止滚动的监听

Android:ScrollView停止滚动的监听

作者:互联网

Android:ScrollView停止滚动的监听

首先判断是否在停止滚动的状态(也可以不用这段代码)
参考https://www.jianshu.com/p/eb4b745afcd0

    public static boolean isfinishScroll(ScrollView scrollView) {
        try {
            if (scrollView != null) {
                Field mScroller = scrollView.getClass().getDeclaredField("mScroller");
                mScroller.setAccessible(true);
                Object object = mScroller.get(scrollView);
                if (object instanceof OverScroller) {
                    OverScroller overScroller = (OverScroller) object;
                    return overScroller.isFinished();
                }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

下面参考https://blog.csdn.net/u011213403/article/details/103704551
isDown记录是否在按下或移动状态,CountDownTimer倒计时100ms结束


    private boolean isDown;//是否在按下或移动状态
    
    private CountDownTimer scrollCountTimer = new CountDownTimer(100, 1){
        @Override
        public void onTick(long millisUntilFinished) {}
        @Override
        public void onFinish() {
            if (isfinishScroll(scrollView)){//其实此时已经停止滚动了,也可以不用isfinishScroll再判断是否已停止滚动。
                //停止滚动后的操作
            }
        }
    };


scrollView的滚动监听setOnScrollChangeListener在API>=23时才可以使用,这里使用getViewTreeObserver().addOnScrollChangedListener()。

        scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                if (!isDown){//惯性滚动时,重新倒计时
                    scrollCountTimer.cancel();
                    scrollCountTimer.start();
                }
            }
        });

调用scrollView的触摸监听setOnTouchListener

        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL://抬起开始倒计时
                        isDown = false;
                        scrollCountTimer.start();
                        break;
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE://按下或移动状态取消倒计时
                        isDown = true;
                        scrollCountTimer.cancel();
                        break;
                }
                return onTouchEvent(event);
            }
        });

标签:isDown,MotionEvent,滚动,ScrollView,监听,scrollCountTimer,scrollView,Android,public
来源: https://blog.csdn.net/Silence_Yong/article/details/117736665