Reputation: 7519
I have placed an image view in my layout, now i need to know its x & y coordinates to draw some stuff over it dynamically.
I tried imageView.getTop();
& imageView.getY()
but they both return "0", but the image is not starting from "0" there is some margin from start and much margin from top.
Is there any other way to get this.
Upvotes: 1
Views: 664
Reputation: 464
To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post:
view.post {
val point = IntArray(2)
view.getLocationOnScreen(point)
val (x, y) = point
}
Values SHOULD no longer be 0 but i had bad experiences with huawei devices. Other way to get x and y coordinates is using viewTreeObserver
view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
view.viewTreeObserver.removeOnGlobalLayoutListener(this)
val point = IntArray(2)
view.getLocationOnScreen(point)
val (x, y) = point
}
});
Possibly you experience some visual glitch with this approach
Upvotes: 1
Reputation: 346
Try with imageView.getLocationOnScreen(int[]) to get X and Y of a view relative to its parent/screen:
int[] positions = new int[2];
imageView.getLocationOnScreen(positions);
int x = positions[0];
int y = positions[1];
Upvotes: 1