Search code examples
javaandroidtouch-event

Measure how far you dragged with onTouchEvent in Android?


Is it possible to measure how far someone has dragged their finger on the display using onTouchEvent? Any ideas would be appreciated.


Solution

  • You can use ACTION_DOWN and ACTION_UP to store start and end point that finger touched and calculate the distance that dragged.

    For example:

    Point p1;
    Point p2;
    
    View view = new View(this);
    
    view.setOnTouchListener(new View.OnTouchListener() {
           public boolean onTouch(View v, MotionEvent event) {
             if(event.getAction() == MotionEvent.ACTION_DOWN)
                p1 = new Point((int) event.getX(), (int) event.getY());
             else if(event.getAction() == MotionEvent.ACTION_UP)
                p2 = new Point((int) event.getX(), (int) event.getY());
    
             return false;
          }
    });
    

    and the distance is equal to Math.sqrt(Math.pow(p1.x-p2.x, 2) + Math.pow(p1.y-p2.y, 2)). And also, if you want to calculate the distance that dragged in any time, you can store the second position if(event.getAction() == MotionEvent.ACTION_MOVE).