[Android View 知识体系] View 的位置与座标系

Photo by Clay Banks on Unsplash

获取View位置的常见方法:

  1. View.getTop、View.getBotoom、View.getLeft、View.getRight
  2. View.getX、 View.getY
  3. View.getTranslationX、View.getTranslationY
  4. View.getLocationInWindow、 View.getLocationOnScreen

View.getTop 等

这些方法获取的都是相对父容器的原始位置,什么是原始位置呢?就是说当View发生移动的时候这些方法的值都是保持不变得。
可以通过这些方法获取View的宽度和高度

width = getRight()- getLeft()
height = getBottom() -getTop()

View.getX、 View.getY

getX = getTranslationX + getLeft
getY = getTranslationY + getTop
表示的相对于父容器的相对位置座标。当 View 没有发生移动的时其实是和 getLeft 相同的

translationX、translationY

translationX 表示的是当前 View 对于父 View 发生的偏移量,一开始的时候 translationX = 0,当 View有移动的时候才会有变化,简单说:当 View 发生移动的时候 getTop、getRight 这些值是不会发生改变的,改变的是表示偏移量的 translationX

getLocatonInWindow()、getLocationOnScreen()

getLocationInWindow() :获取的是一个控件在其所在 window 的座标位置
getLocationOnScreent(): 获取的是控件在屏幕上的座标位置

在这里插入图片描述

getLocationInWindow()是以B为原点的C的座标。
getLocationOnScreen 以A为原点,包括了状态栏的高度

一般情况下一个正常的 Activity 的 Window 是充满屏幕的,所以这两个方法将会返回同样的 x 和 y 座标,仅仅在一些特殊的场景下,例如 dialog 他有属于自己的 window 这个 Acitivty 的 Window 和屏幕是存在偏移量的,这两个方法返回的结果将不同。

**注意:**这两个方法在 Activity 的 onCreate 中获取的座标永远是0,要等 UI 控件都加载完成之后才能获取。在onWindowFocusChanged() 中获取最好。因为在生命周期:onCreate、onStart、onResume中真正的View都没有可见。

引自 onWindowFocusChanged() 官方文档:

Called when the current Window of the activity gains or loses focus. This is the best indicator of whether this activity is visible to the user. The default implementation clears the key tracking state, so should always be called.

参考 staticoverflow

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章