我不确定你的问题,但似乎你正试图在你的 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;
}
}
}