Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ImageView's getX, getY, setX and setY do not represent the actual value in the Relative Layout?

I am trying to make a simple app just to understand better how to use Touch events on Android. Right now, my Activity just moves an ImageView to the coordinates of the touch on the screen (the MotionEvent's coordinates). I could manage to do this by applying a simple trick to set the new position of the image to a value that is made of the touch coordinates relative to the position of the image (getX() and getY()). The dx and dy variables are responsible to store this relative values so the touch keeps constant within the image.

Now I want to put 2 ImageViews in the Activity and have only two fixed spots for ImageViews and once the user drags one ImageView over the other ImageView's center, the two images switch places, but to do that correctly I would like to get the real coordinates of the image center. I commented the parts of the code that make it work correctly to show the issue. As you can see in the first picture when the view is created, the Image Coordinates are simply (0, 0), no matter where it is (as long as the initial position is defined as a layout parameter like CENTER_IN_PARENT).

As you can see in the second picture and as far as I observed ImageView's getX() and getY() return the coordinate as if the top-left corner of the image was in the top-left corner of the DISPLAY when the image is located at the top-left corner of the ACTIVITY WINDOW.

I would like to understand why that happens and if anyone knows how to actually get the coordinates of ImageView that can be directly compared to the coordinates of MotionEvent.


Pictures:

FIRST PICTURE

SECOND PICTURE

like image 516
Thomas H. Avatar asked Jul 01 '13 18:07

Thomas H.


1 Answers

I still don't know exactly why getX(), getY(), setX(), and setY() do not represent the position of the View on the screen, but I figured out how to get the actual location of the view objects on the screen: getLocationOnScreen(coordinates). Where coordinates is a 2 position int array (int[2]).

For example, to get the real value correspondent to the top-left corner of my ImageView image I simply need to do something like:

int[] img_coordinates = new int[2];
ImageView image = (ImageView) findViewById(R.id.myImage);

image.getLocationOnScreen(img_coordinates);

And then I can actually compare these coordinates with the Touch-event's getRawX and getRawY.

If I want to get the center point of my view I just need to do this:

x_center = (double)img_coordinates[0] + image.getWidth()/2.0;
y_center = (double)img_coordinates[1] + image.getHeight()/2.0;

I hope this helps other people too, it took me a while to find this approach and I am actually not sure if it is the best approach but it does the trick for me.

like image 189
Thomas H. Avatar answered Oct 23 '22 13:10

Thomas H.