MotionEvent GetY() and getX() return incorrect values
Asked Answered
O

3

19

I have following situation:

I have a custom ListView with ImageView and TextView in a row. The ImageView has an onTouchListener, wchich invokes my onTouch method. Here are some lines from it:

if (event.getAction()==MotionEvent.ACTION_MOVE) {
    layout.leftMargin = (int) event.getX() - dragIcon.getWidth()/2;         
    layout.topMargin = (int) event.getY() - dragIcon.getHeight()/2;
    //Log.d("Tag", "Pozycja: " +  event.getX() +", "+  event.getY());
}
dragIcon.setLayoutParams(layout);

When move is detected I'm showing up new image (not this in ListView) and I'm starting to move it according to x and y coordinates.

The problem is, that getX and getY return positions relative to ImageView in the list, not the whole ListView (I think so). So when I touch an item in the middle and swipe finger up, then getY returns negative values (above ImageView boundary).

Hope, I explained clearly..

Any ideas how to get this coordinates relative to the screen size? Thank you.

Offcolor answered 4/6, 2011 at 14:11 Comment(1)
See also Difference between MotionEvent.getRawX and MotionEvent.getXAdmixture
O
49

Try using getRawX() and getRawY() instead of getX() and getY().

Olla answered 4/6, 2011 at 15:23 Comment(1)
in my case both y and rawY are incorrect for cancel motion event in onTouchListener in ViewHolder in recycleview with simpleselection.Mozzarella
B
6

getX() and getY() returns the values respective to the views that it was called on. Hence Let's say,

ImageView imV = (ImageView)findViewById(R.id.image_view);

Then you can get x,y using

x = imV.getX() + event.getX();
y = imV.getY() + event.getY();

Here I assume you have set the onTouchListener on imV.

Baeda answered 6/4, 2017 at 8:42 Comment(1)
You saved me. This works great. getRawX(), getRawY() didn't helped me.Befitting
I
0

Here's the full answer. This captures the last 3 events on a temporary variable: https://mcmap.net/q/665344/-how-to-get-correct-coords-event-getx-event-gety-of-object-with-ontouchlistener

Intemerate answered 30/1, 2019 at 10:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.