前言
獲取 View 座標在 Android 開發中非常常見。今天carson將詳細給大家講解 獲取 View 座標常用6種方式:
getLeft()、getTop()、getRight()、getBottom()
getX()、getY()、getRawX()、getRawY()
getLocationOnScreen()
getLocationInWindow()
getGlobalVisibleRect()
getLocalVisibleRect()
方式1:getLeft()、getTop()、getRight()、getBottom()
1. 應用場景
獲得 View 相對 父View 的座標
2. 使用
view.getLeft();view.getTop();view.getRight();view.getBottom();
3. 具體描述
View的位置由4個頂點決定的(如下A、B、C、D)
View的頂點
4個頂點的位置描述分別由4個值決定:(請記住:View的位置是相對於父控件而言的)
方式2:getX()、getY()、getRawX()、getRawY()
1. 應用場景
獲得點擊事件處 相對點擊控件 & 屏幕的座標
2. 使用
該方式是通過motionEvent獲取的
motionEvent event;event.getX(); event.getY();event.getRawX(); event.getRawY();
3. 具體介紹
方式3:getLocationInWindow()
1. 應用場景
獲取控件 相對 窗口Window 的位置
2. 具體使用
int[] location = new int[2];view.getLocationInWindow(location);int x = location[0]; // view距離window 左邊的距離(即x軸方向)int y = location[1]; // view距離window 頂邊的距離(即y軸方向)// 注:要在onWindowFocusChanged()裏獲取,即等window窗口發生變化後
3. 示意圖
方式4:getLocationOnScreen()
1. 應用場景
獲得 View 相對 屏幕 的絕對座標
2. 使用
int[] location = new int[2];view.getLocationOnScreen(location);int x = location[0]; // view距離 屏幕左邊的距離(即x軸方向)int y = location[1]; // view距離 屏幕頂邊的距離(即y軸方向)// 注:要在view.post(Runable)裏獲取,即等佈局變化後
3. 示意圖
方式5:getGlobalVisibleRect()
1. 應用場景
View可見部分 相對於 屏幕的座標。
2. 具體使用
Rect globalRect = new Rect();view.getGlobalVisibleRect(globalRect);globalRect.getLeft();globalRect.getRight();globalRect.getTop();globalRect.getBottom();
3. 示意圖
方式6:getLocalVisibleRect()
1. 應用場景
View可見部分 相對於 自身View位置左上角的座標。
2. 具體使用
Rect localRect = new Rect();view.getLocalVisibleRect(localRect);localRect.getLeft();localRect.getRight();localRect.getTop();localRect.getBottom();
3. 示意圖
總結
本文對Android獲取View座標位置的方式進行了全面講解,總結如下:
最後
感謝大家能耐着性子,看完我囉哩囉嗦的文章。
願與各位堅守在Android開發崗位的同胞們互相交流學習,共同進步!
在這裏我也分享一份自己收錄整理的Android學習PDF+架構視頻+面試文檔+源碼筆記,還有高級架構技術進階腦圖、Android開發面試專題資料,高級進階架構資料幫助大家學習提升進階,也節省大家在網上搜索資料的時間來學習,也可以分享給身邊好友一起學習