ScrollView内部的View中的OnTouchListener

时间:2019-01-22 10:33:21

标签: android android-scrollview ontouchlistener

我在ScrollView内部有一个View。我想每80毫秒调用一次方法,只要用户按住该View键即可。这就是我已经实现的:

final Runnable vibrate = new Runnable() {
    public void run() {
        vibrate();
    }
};

theView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            final ScheduledFuture<?> vibrateHandle =
                    scheduler.scheduleAtFixedRate(vibrate, 0, 80, MILLISECONDS);
            vibrateHanlers.add(vibrateHandle);
            return true;
        }
        if (motionEvent.getAction() == MotionEvent.ACTION_CANCEL
                || motionEvent.getAction() == MotionEvent.ACTION_UP) {
            clearAllScheduledFutures();
            return false;
        }
        return true;
    }
});

问题在于,ACTION_CANCEL被要求移动到最小的手指。我知道这是因为View位于ScrollView内部,但是我不确定在这里有什么选择。我是否创建自定义ScrollView,并尝试查找是否触摸了所需的视图并禁用了ScrollView的触摸事件?还是为小移动阈值而禁用SrollView的触摸事件?还是其他?

2 个答案:

答案 0 :(得分:0)

您是否可以尝试在ActionUp事件中返回true而不是false,以使该事件被视为消耗

if (motionEvent.getAction() == MotionEvent.ACTION_CANCEL
                || motionEvent.getAction() == MotionEvent.ACTION_UP) {
            clearAllScheduledFutures();
            return true;
        }

答案 1 :(得分:0)

这是我修复它的方式。

我创建了自定义ScrollView

public class MainScrollView extends ScrollView {
    private boolean shouldStopInterceptingTouchEvent = false;

    public void setShouldStopInterceptingTouchEvent(boolean shouldStopInterceptingTouchEvent) {
        this.shouldStopInterceptingTouchEvent = shouldStopInterceptingTouchEvent;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (shouldStopInterceptingTouchEvent)
            return false;
        else
            return super.onInterceptTouchEvent(ev);
    }
}

在onTouchEvent中:

theView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            svMain.setShouldStopInterceptingTouchEvent(true);
            final ScheduledFuture<?> vibrateHandle =
                    scheduler.scheduleAtFixedRate(vibrate, 0, 80, MILLISECONDS);
            vibrateHanlers.add(vibrateHandle);
            return true;
        }
        if (motionEvent.getAction() == MotionEvent.ACTION_CANCEL
                || motionEvent.getAction() == MotionEvent.ACTION_UP) {
            svMain.setShouldStopInterceptingTouchEvent(false);
            clearAllScheduledFutures();
            return false;
        }
        return true;
    }
});

因此,我决定在touchEvent的{​​{1}}中决定何时停止拦截ScrollView中的onTouchListener