8

Given a TextView, is it possible to know at runtime the X and Y coordinates of where it is drawn? Is it also possible to know the size (width/length) in pixels?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
michelemarcon
  • 23,277
  • 17
  • 52
  • 68

2 Answers2

14

There are getLeft(), getTop(), getWidth(), getHeight() methods for a view, it works for textView too. for more information , see the following link...

getLeft() and getTop() will return you the starting x,y co-ordinates.

http://developer.android.com/reference/android/view/View.html

Yashwanth Kumar
  • 28,931
  • 15
  • 65
  • 69
  • 3
    This give me always value '0'. This can not helpful to me, can you help me? suggest any other solution plz. – Yog Guru Sep 25 '13 at 11:47
  • 1
    @YogGuru, you could also try `getLocationInWindow`, `getLocationOnScreen`, because `getLeft` and `getTop` are relative to view parent. – Stan Oct 19 '13 at 12:56
  • @Stan Hey..!! It was my mistake i do try to get this in Oncreat method it always gives '0' but when i try to get in ontouch method it gives me value. – Yog Guru Oct 21 '13 at 05:19
  • 4
    these return the position relative to the parent, not the absolute position. – Jeffrey Blattman Apr 12 '14 at 01:23
4

Coordinates relative to parent

int x = textView.getLeft();
int y = textView.getTop();

Absolute coordinates

int[] location = new int[2];
textView.getLocationOnScreen(location);
int x = location[0];
int y = location[1];

See this answer for more.

Pixel size

int width = textView.getWidth();
int height = textView.getHeight();

Notes

  • If you are getting (0,0) it could be because you are getting the relative coordinates related to the parent layout (and it is sitting in the top left corner of the parent). It could also be because you are trying to get the coordinates before the view has been laid out (for example, in onCreate()).
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393