【发布时间】:2021-01-02 19:32:13
【问题描述】:
我在布局中放置了一个图像视图,现在我需要知道它的 x 和 y 坐标才能在其上动态绘制一些东西。
我尝试了imageView.getTop(); 和imageView.getY(),但它们都返回“0”,但图像不是从“0”开始,从开始有一些边距,从顶部有很多边距。
有没有其他方法可以得到这个。
【问题讨论】:
标签: android android-layout android-constraintlayout
我在布局中放置了一个图像视图,现在我需要知道它的 x 和 y 坐标才能在其上动态绘制一些东西。
我尝试了imageView.getTop(); 和imageView.getY(),但它们都返回“0”,但图像不是从“0”开始,从开始有一些边距,从顶部有很多边距。
有没有其他方法可以得到这个。
【问题讨论】:
标签: android android-layout android-constraintlayout
为确保视图有机会更新,请在使用 view.post 计算出视图的新布局后运行您的位置请求:
view.post {
val point = IntArray(2)
view.getLocationOnScreen(point)
val (x, y) = point
}
值不应再为 0,但我在使用华为设备时有过不好的体验。获取 x 和 y 坐标的其他方法是使用 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
}
});
您可能会在使用这种方法时遇到一些视觉故障
【讨论】:
尝试使用 imageView.getLocationOnScreen(int[]) 来获取视图相对于其父/屏幕的 X 和 Y:
int[] positions = new int[2];
imageView.getLocationOnScreen(positions);
int x = positions[0];
int y = positions[1];
【讨论】: