对于getLocationOnScreen()、x 和y 将返回视图的左上角。
使用getLocationInWindow() 将相对于其容器,而不是整个屏幕。如果您的根布局小于屏幕(如在对话框中),这将与 getLocationOnScreen() 不同。在大多数情况下,它们是相同的。
注意:如果值始终为 0,您可能会在请求位置之前立即更改视图。您可以使用 view.post 来确保值可用
Java 解决方案
int[] point = new int[2];
view.getLocationOnScreen(point); // or getLocationInWindow(point)
int x = point[0];
int y = point[1];
为确保视图有机会更新,请在使用 view.post 计算视图的新布局后运行您的位置请求:
view.post(() -> {
// Values should no longer be 0
int[] point = new int[2];
view.getLocationOnScreen(point); // or getLocationInWindow(point)
int x = point[0];
int y = point[1];
});
~~
Kotlin 解决方案
val point = IntArray(2)
view.getLocationOnScreen(point) // or getLocationInWindow(point)
val (x, y) = point
为确保视图有机会更新,请在使用 view.post 计算视图的新布局后运行您的位置请求:
view.post {
// Values should no longer be 0
val point = IntArray(2)
view.getLocationOnScreen(point) // or getLocationInWindow(point)
val (x, y) = point
}
我建议创建一个扩展函数来处理这个问题:
// To use, call:
val (x, y) = view.screenLocation
val View.screenLocation get(): IntArray {
val point = IntArray(2)
getLocationOnScreen(point)
return point
}
如果您需要可靠性,还请添加:
// To use, call:
view.screenLocationSafe { x, y -> Log.d("", "Use $x and $y here") }
fun View.screenLocationSafe(callback: (Int, Int) -> Unit) {
post {
val (x, y) = screenLocation
callback(x, y)
}
}