3

One of the activities in my Android app has a relative layout with two imageviews, which are set up in an xml layout file. How can I programmatically get x,y location of the imageviews

Will these coordinates be different dependent on screen size and density?

What I want to do is have the user touch image1 which will then be animated to move to the location of image2.

Obviously, since I placed these images in the xml I know their x,y coordinates, but I'm concerned that these coordinates will vary dependent on the screen size and density.

Tori
  • 1,358
  • 4
  • 19
  • 38
  • and what will be the position of image2 ? – SALMAN Jul 23 '12 at 19:16
  • Also when you place the `ImageView` in xml, make sure you are using 30dp instead of 30px. Check here for what that means: http://stackoverflow.com/questions/2025282/difference-of-px-dp-dip-and-sp-in-android – Salil Pandit Jul 23 '12 at 19:56

2 Answers2

9

You can use View.getTop(), View.getBottom(), View.getLeft(), and View.getRight(). These will return the location of the top, bottom, left and right edge of the View relative to the parent.

duggu
  • 37,851
  • 12
  • 116
  • 113
Jason Crosby
  • 3,533
  • 4
  • 28
  • 49
  • As per this post http://stackoverflow.com/a/20991950/2162226, the view needs to have been actually rendered in order for the methods to work correctly: *"You need your view added to a layout and displayed (At least one layout pass and measure pass must have run.)"*. Thanks for the solt! – Gene Bo Feb 02 '16 at 02:57
1

How to get x and y

int[] t = new int[2];
int[] cordinatesofImageView1 = imageView1.getLocationOnScreen(t);


int[] cordinatesofImageView2 = imageView2.getLocationOnScreen(t);

You have to adjust your control w.r.t of screen size and Here is the link that how can you detect that.

Determine device screen category (small, normal, large, xlarge) using code

OR

You can refer to this answer this may help you.

Interchange location of two views

Thanks :)

Community
  • 1
  • 1
SALMAN
  • 2,031
  • 1
  • 20
  • 18
  • There's no getX, getY methods on an imageView. It's getTop, getLeft, getBottom, getRight as Jason describes in his answer below. – Tori Jul 23 '12 at 20:06
  • Sorry for the inconvenience I have edited my code, this time it will surely help you. Thanks :) – SALMAN Jul 23 '12 at 20:22