Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 681
William L. Avatar asked Feb 02 '26 12:02

William L.


1 Answers

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).

like image 53
Hossein Mobasher Avatar answered Feb 05 '26 00:02

Hossein Mobasher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!