How to get initial X, Y values (of first touch ACTION_DOWN) in OnTouchListener
-
21-12-2019 - |
Question
I need initial x and y values (the point that moving begun with first touch ACTION_DOWN
) in order to calculate deltaX
and deltaY
as follows;
private float mInitialTouchX = Float.NaN; // # First touch temp var defined globally
...
someView.setOnTouchListener(new OnTouchListener() {
@Override public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_MOVE:
MoveViewHorizontally(v, event.getX(), mInitialTouchX);
break;
case MotionEvent.ACTION_DOWN:
mInitialTouchX = event.getX(); // # Set initial touch point
break;
case MotionEvent.ACTION_UP:
mInitialTouchX = Float.NaN; // # Reset initial touch point
break;
default: break;
}
return false;
}
});
private void MoveViewHorizontally(View v, float x, float initialTouchX)
{
int deltaX = (int)(x - initialTouchX);
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
layoutParams.leftMargin += deltaX;
v.setLayoutParams(layoutParams);
}
Is there a way that i can get initial touch values from event
or somehow - somewhere else, avoiding usage of global variable mInitialTouchX
?
Solution
Nope, there is no better way. You're doing it the right way. In fact, if you take a look at the code for GestureDetector
, you will see that they are doing it more or less the same way.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow