Can I get a View's x and y position relative to the root layout of my Activity in Android?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
This is one solution, though since APIs change over time and there may be other ways of doing it, make sure to check the other answers. One claims to be faster, and another claims to be easier.
Let me know if that works.
It should recursively just add the top and left positions from each parent container. You could also implement it with a
Point
if you wanted.Incase someone is still trying to figure this out. This is how you get the center X and Y of the
view
.First I get the root layout then calculate the coordinates difference with the view.
You can also use the
getLocationOnScreen()
instead ofgetLocationInWindow()
.I just found the answer here
It says: 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.
so use:
No need to calculate it manually.
Just use getGlobalVisibleRect like so:
Also note that for the centre coordinates, rather than something like:
You can just do:
The Android API already provides a method to achieve that. Try this:
Here is the doc