Android 获取 View 在屏幕中的位置

我们在开发过程中,有时候需要获取一个 View 在屏幕中的位置,比如这个 View 是否在屏幕中显示,还是在屏幕之外等等。

我们可以通过位置,对其做一些操作,以便完成我们的业务需求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
val location = IntArray(2)
it.getLocationOnScreen(location)
val x = location[0]
val y = location[1]
Log.d("TAG", "getLocationOnScreen x = $x ; y = $y")

it.getLocationInWindow(location)
val x1 = location[0]
val y2 = location[1]
LogUtil.d("TAG", "getLocationInWindow x1 = $x1 ; y2 = $y2")

Log.d("TAG", "left:" + it.left)
Log.d("TAG", "right:" + it.right)
Log.d("TAG", "Top:" + it.top)
Log.d("TAG", "bottom:" + it.bottom)
Log.d("TAG", "width:" + it.width)
Log.d("TAG", "height:" + it.height)

getLocationOnScreenView 相对于物理手机屏幕的位置。

getLocationInWindowView 相对于窗口的位置,Window 是安卓系统中的一个类,不包括状态栏。

View 的 left、top、right、bottom 是它在父 View 中的位置。