Implementing the Drag Gesture

A drag gesture starts when the first finger is pressed to the screen (ACTION_DOWN) and ends when it is removed (ACTION_UP or ACTION_ POINTER_UP).

Download Touchv1/src/org/example/touch/Touch.java

switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); Log.d(TAG, "mode=DRAG"); mode = DRAG; break;

case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = NONE;

case MotionEvent.ACTION_MOVE: if (mode == DRAG) {

matrix.set(savedMatrix);

matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);

break;

When the gesture starts, we remember the current value of the transformation matrix and the starting position of the pointer. Every time the finger moves, we start the transformation matrix over at its original value and call the postTranslate() method to add a translation vector, the difference between the current and starting positions.

If you run the program now, you should be able to drag the image around the screen using your finger. Neat, huh?

0 0

Post a comment