Android View獲取坐標的方式:
1. 獲取View相對於父View的坐標:View view.getLeft()、view.getTop()、view.getRight()、view.getBottom()
2.獲取點擊事件的點擊位置相對於其點擊控件的坐標,以及相對於屏幕的坐標。 motionEvent event.getX()、event.getY()、event.getRawX()、event.getRawY()
3. 獲取控件 相對 窗口Window 的位置:getLocationInWindow(),獲取不到的時候可能因為要在onWindowFocusChanged()里獲取,即等window窗口發生變化后才可以
int[] location = new int[2];
view.getLocationInWindow(location);
int x = location[0]; // view距離window 左邊的距離(即x軸方向)
int y = location[1]; // view距離window 頂邊的距離(即y軸方向)
4.獲得 View 相對 屏幕 的絕對坐標:getLocationOnScreen(),要在view.post(Runable)里獲取,即等布局變化后
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0]; // view距離 屏幕左邊的距離(即x軸方向)
int y = location[1]; // view距離 屏幕頂邊的距離(即y軸方向)
5.View可見部分 相對於 屏幕的坐標:getGlobalVisibleRect()
Rect globalRect = new Rect();
view.getGlobalVisibleRect(globalRect);
globalRect.getLeft();
globalRect.getRight();
globalRect.getTop();
globalRect.getBottom();
6. View可見部分 相對於 自身View位置左上角的坐標。
Rect localRect = new Rect();
view.getLocalVisibleRect(localRect);
localRect.getLeft();
localRect.getRight();
localRect.getTop();
localRect.getBottom();