I have a View
which I want to be draggable so I've overridden its onTouchEvent(MotionEvent event)
method and, on move events, I reposition/translate my View
based on the event action's (x, y) coordinates. However! On dragging my View
right - for example - I'm seeing that the event action's x co-ordinate is not increasing steadily (i.e. ... 15, 16, 17, 18...) but is interleaved instead (i.e. ... 15, 23, 16, 24, 17, 25 ...) and thus my View
moves in a jerked manner. (Likewise for dragging left, up, down etc.)
Anyone know why this might be and how I can avoid it?!
Here's my onTouchEvent(..)
method...
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
// make note of the down action's (x, y) coordinate
action_down_x = event.getX();
action_down_y = event.getY();
return true;
case MotionEvent.ACTION_MOVE:
// work out displacement
dX = event.getX() - action_down_x;
dY = event.getY() - action_down_y;
// code here to move the view
return true;
case MotionEvent.ACTION_UP:
return true;
}
return super.onTouchEvent(event);
}
The problem is pretty simple: You are working with two relative coordinates. If you override the onTouchEvent()
from the view, you might get a value 10,10. If you now move the finger, you get a new value, lets say 9,9 so you change the position of the view which would result in the fact, that your finger is at 10,10 of the view coordinate system again.
What I would do: Override the onTouchEvent()
of the parent, so that you stay in the same coordinate system. Your implementation looks good, so it should work easily when you just move the code to the parent view/activity.