简短版本:我想要一种方法来在 onTouchEvent 上启动基于时间的计数器,并测试在响应之前是否已经过了一定的时间,作为手动 LongTouch 检测。
解释:
我有一个自定义 imageView,可以通过两根手指滑动滑入/滑出屏幕。我想向其中添加拖动事件,但这些事件需要比长按更快。我可以通过使用每个 onTouchEvent 更新一次的计数器来延迟拖动事件,并且仅在计数(例如 10 次)时触发拖动,但计数器仅在触摸事件时更新,并且手指必须在移动。
如何创建基于时间的计数器、每秒递增 60 次的活动级别字段或类似内容?
我不确定你的问题,但似乎你正在尝试在 onTouchListener 中实现捕获长点击事件,除非你需要在 ACTION_UP 事件发生之前执行某种逻辑?如果是这样,那就是我遇到的同样的问题。我也尝试过使用 System.nanoTime() 但我发现了一个不太棘手的方法。您可以使用计时器,您只需将其安排在第一个 ACTION_DOWN 事件上,并在发生任何不利情况时取消它(例如 ACTION_UP 这意味着它不是长按,而只是单击,或者 ACTION_MOVE 位移超过一定的阈值)。像下面这样:
layout.seyOnTouchListener(new OnTouchListener(){
private Timer longpressTimer; //won't depend on a motion event to fire
private final int longpressTimeDownBegin = 500; //0.5 s
private Point previousPoint;
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:{
longPressTimer = new Timer();
longpressTimer.schedule(new TimerTask(){
//whatever happens on a longpress
}, longpressTimeDownBegin);
return true; //the parent was also handling long clicks
}
case MotionEvent.ACTION_MOVE:{
Point currentPoint = new Point((int)event.getX(), (int)event.getY());
if(previousPoint == null){
previousPoint = currentPoint;
}
int dx = Math.abs(currentPoint.x - previousPoint.x);
int dy = Math.abs(currentPoint.y - previousPoint.y);
int s = (int) Math.sqrt(dx*dx + dy*dy);
boolean isActuallyMoving = s >= minDisToMove; //we're moving
if(isActuallyMoving){ //only restart timer over if we're actually moving (threshold needed because everyone's finger shakes a little)
cancelLongPress();
return false; //didn't trigger long press (will be treated as scroll)
}
else{ //finger shaking a little, so continue to wait for possible long press
return true; //still waiting for potential long press
}
}
default:{
cancelLongPress();
return false;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)