How to get the X Y coordinates and pixel size of a TextView?

空扰寡人 提交于 2019-12-09 17:07:17

问题


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?


回答1:


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




回答2:


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()).


来源:https://stackoverflow.com/questions/7905371/how-to-get-the-x-y-coordinates-and-pixel-size-of-a-textview

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