MotionEvent GetY() and getX() return incorrect values

一笑奈何 提交于 2019-12-18 14:50:10

问题


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.


回答1:


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




回答2:


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.




回答3:


Here's the full answer. This captures the last 3 events on a temporary variable: https://stackoverflow.com/a/54438485/1931228



来源:https://stackoverflow.com/questions/6237200/motionevent-gety-and-getx-return-incorrect-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!