tags:

views:

65

answers:

2

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.

A: 

Your best bet would be to deal with the MotionEvent's you get from a View.OnTouchListener() callback. The motion events keep track of how you are currently interacting with the View by its action property.

I would imagine you can calculate which direction someone slides their finger by examining the action property of the MotionEvents and the x/y values of where the motion event took place.

if(action == MotionEvent.ACTION_MOVE) {
  int newX = motionEvent.getX();
  int newY = motionEvent.getY();

  int deltaX = oldX - newX;
  int deltaY = oldY - newY;

  //determine which direction finger moved
}

There are lots of other method available on the MotionEvent object for use as well: http://developer.android.com/reference/android/view/MotionEvent.html

nicholas.hauschild
+2  A: 

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;
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();
            float dx = x2-x1;
            float 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 = "up";
                else direction = "down";
            }
        }
        }
sirconnorstack