'Event.getX() gets wrong values when using onTouchListener
Here is the first code:
btn1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v,MotionEvent event) {
int x_cursor = (int) event.getX();
x_initial_touch = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x_initial_touch = event.getX();
break;
case MotionEvent.ACTION_MOVE:
System.out.println(event.getX())
btn1.animate().translationX(x_cursor - x_initial_touch ).setDuration(0);
break;
}
return false;
}
});
Here is the secoond code:
btn1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v,MotionEvent event) {
int x_cursor = (int) event.getX();
x_initial_touch = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x_initial_touch = event.getX();
break;
case MotionEvent.ACTION_MOVE:
System.out.println(event.getX())
any_other_button.animate().translationX(x_cursor - x_initial_touch ).setDuration(0);
break;
}
return false;
}
});
In first code, when i drag the button to the left, the values that are printed are: 57 56 57 55 57 54 57 53 and so on...
And in second code, when i drag the button to the left, the values that are printed are: 57 56 55 54 53 52 51 50 and so on...(which is very good, and what i want). My question is why in the first code, when I try to drag a button by touching and dragging IT the event.getX() is making some steps back and then continue. I am asking this because as you can figure the button won't move smooth and it will come back for a milisec to start position. Hope you understant what I want to say.
EDIT I've solve the issue using event.getRawX(); instead of event.getX();
Solution 1:[1]
Your x_cursor and x_initial_touch are both equal to event.getX(), so the argument of your translationX call is always zero, which resets the initial position. Thus, after each move you get one more event which corresponds to resetting your initial position. If you translate any_other_button, then it will not send the event to btn1 when its position is reset, so you don't see the interleaving 57's in the second case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Sveshnikov |
