[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

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