检测ScrollView上的结束

Chr*_*rry 10 android onfling android-scrollview

我已经覆盖ScrollView了将MotionEvents 传递给a GestureDetector来检测ScrollView上的fling事件.我需要能够检测到滚动停止的时间.这与MotionEvent.ACTION_UP事件不一致,因为这通常发生在fling手势的开始,随后onScrollChanged()是ScrollView上的一连串调用.

所以基本上我们在这里处理的是以下事件:

  1. onFling
  2. onScrollChanged,onScrollChanged,onScrollChanged,...,onScrollChanged

触发onScrollChanged事件时没有回调.我正在考虑使用HandleronFling期间向事件队列发送消息并等待Runnable执行以指示fling 结束,不幸的是它在第一次onScrollChanged调用之后触发.

还有其他想法吗?

Pau*_*rke 17

我结合了这里的一些答案来构建一个类似于AbsListView它的方式的工作监听器.它基本上就是你所描述的,它在我的测试中运作良好.

注意:您可以简单地覆盖ScrollView.fling(int velocityY)而不是使用自己的GestureDetector.

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

public class CustomScrollView extends ScrollView {

    private static final int DELAY_MILLIS = 100;

    public interface OnFlingListener {
        public void onFlingStarted();
        public void onFlingStopped();
    }

    private OnFlingListener mFlingListener;
    private Runnable mScrollChecker;
    private int mPreviousPosition;

    public CustomScrollView(Context context) {
        this(context, null, 0);
    }

    public CustomScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mScrollChecker = new Runnable() {
            @Override
            public void run() {
                int position = getScrollY();
                if (mPreviousPosition - position == 0) {
                    mFlingListener.onFlingStopped();
                    removeCallbacks(mScrollChecker);
                } else {
                    mPreviousPosition = getScrollY();
                    postDelayed(mScrollChecker, DELAY_MILLIS);
                }
            }
        };
    }

    @Override
    public void fling(int velocityY) {
        super.fling(velocityY);

        if (mFlingListener != null) {
            mFlingListener.onFlingStarted();
            post(mScrollChecker);
        }
    }

    public OnFlingListener getOnFlingListener() {
        return mFlingListener;
    }

    public void setOnFlingListener(OnFlingListener mOnFlingListener) {
        this.mFlingListener = mOnFlingListener;
    }

}
Run Code Online (Sandbox Code Playgroud)