I have a button in my activity. How can I get all of its 4 coordinates?
How can I get x1,x2,y1 and y2? Sorry if its too dumb.
Thanks!
I have a button in my activity. How can I get all of its 4 coordinates?
How can I get x1,x2,y1 and y2? Sorry if its too dumb.
Thanks!
PointF y1 = new PointF(button.getX(), button.getY());
PointF y2 = new PointF(button.getX(), button.getY() + button.getWidth());
PointF x1 = new PointF(button.getX() - button.getHeight(), button.getY());
PointF x2 = new PointF(button.getX() - button.getHeight(), button.getY() + button.getWidth());
I believe getTop()
, getBottom()
, getRight()
, getLeft()
methods that @LokiSinclair mentioned would also work. Do make sure you call these methods in onWindowFocusChanged()
because calling these methods will yield 0 in onCreate()
or onStart()
.
You can use the methods; getTop()
, getLeft()
, getBottom()
and getRight()
in the View Class.
From the official docs:
Position
The geometry of a view is that of a rectangle. A view has a location, expressed as a pair > of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.
It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the > view. The latter returns the top, or Y, coordinate of the rectangle representing the view. > These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.
In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth() (see Size for more information about the width.)
One thing to be aware of though, is the view has to have been drawn at least once, before attemping to get position details.
Depends on what you want.
You can use getTranslationX() and getTranslationY() methods to get the original position of the view in the screen regardless the layout that belongs your view.
getX() and getY() methods to get the position of your view respective the father layout of your view.
If you decide which approach fits to your problem, you will combine the methods with the view.getWidth and view.getHeight methods in order to get the values that you want.