如何捕获的Andr​​oid手机的手指移动的方向吗?手指、方向、手机、Andr

2023-09-05 08:30:16 作者:凌云之上,信自己

我想捕捉的Andr​​oid触控手机的手指移动的方向。如果用户滑动手指在上/下/左/右方向,我想抓住这个方向发展。我如何才能找到呢?谢谢你。

I want to capture the finger movement direction on Android touch phone. If a user slides his finger in up/down/left/right direction, I want to capture this direction. How can I find this? Thanks.

推荐答案

实施的onTouchEvent(),并在用户presses下来,抬起计算dx和dy。您可以使用这些值来计算出的移动方向。

Implement onTouchEvent(), and calculate dx and dy by where the user presses down and lifts up. You can use these values to figure out the direction of the move.

float x1, x2, y1, y2, dx, dy;
String direction;
switch(event.getAction()) {
    case(MotionEvent.ACTION_DOWN):
        x1 = event.getX();
        y1 = event.getY();
        break;
    case(MotionEvent.ACTION_UP) {
        x2 = event.getX();
        y2 = event.getY();
        dx = x2-x1;
            dy = y2-y1;

            // Use dx and dy to determine the direction
        if(Math.abs(dx) > Math.abs(dy)) {
            if(dx>0) directiion = "right";
            else direction = "left";
        } else {
            if(dy>0) direction = "down";
            else direction = "up";
        }
    }
}