Search code examples
androidperformancegesture

Get speed of a onTouch ACTION_MOVE event in Android


This should be a pretty simple thing to do. The user puts his finger on the screen and drags it around the screen. There are two events firing on onTouch:

  • MotionEvent.ACTION_DOWN
  • MotionEvent.ACTION_MOVE

Now, how can I calculate the speed of the ACTION_MOVE gesture ? The user drags the finger slower or faster during a gesture, so I think I need to calculate the speed between two intermediate touched points: the lastTouchedPointX,lastTouchedPointY and the event.getX(),event.getY().

Has anyone done this before ?


Solution

  • @Override
            public boolean onTouchEvent(MotionEvent event, MapView mapView) {
    
    
                if(event.getAction() == MotionEvent.ACTION_DOWN) {
    
                    oldX = event.getX();
                    oldY = event.getY();
                        //start timer
    
                } else if (event.getAction() == MotionEvent.ACTION_UP) {   
    
                    //long timerTime = getTime between two event down to Up
                    newX = event.getX();
                    newY = event.getY();
    
                    float distance = Math.sqrt((newX-oldX) * (newX-oldX) + (newY-oldY) * (newY-oldY));
                    float speed = distance / timerTime;
    
                }
    }