View的可見性檢查
- getLeft()、getTop()、getRight()、getBottom()
- getX()、getY()、getRawX()、getRawY()
- getLocationOnScreen()
- getLocationInWindow()
- getGlobalVisibleRect()
- getLocalVisibleRect()
方式一:getLeft()/getTop()/getRight()/getBottom()
獲取當前View相對于父View的坐標
view.getLeft()
view.getTop()
view.getRight()
view.getBottom()
方式二:getX()/getY()/getRawX()/getRawY()
獲取點擊事件相對直接控件的發(fā)生坐標或相對屏幕的坐標
MotionEvent event
event.getX()
event.getY()
event.getRawX()
event.getRawY()
方式三:getLocationOnScreen()
獲取當前View相對于屏幕的坐標
int[] location = new int[2];
view.getLocationOnScreen(location);
// view距離屏幕左邊的距離
int x = location[0];
// view距離屏幕頂邊的距離
int y = location[1];
// 在view.post(Runnable)里獲取,即等布局變化后
方式四:getLocationInWindow()
獲取當前View相對于所在Window的坐標
int[] location = new int[2];
view.getLocationInWindow(location);
// view距離window左邊的距離
int x = location[0];
// view距離window頂邊的距離
int y = location[1];
// 在onWindowFocusChanged()里獲取,即等window窗口發(fā)生變化后
方式五:getGlobalVisibleRect()
獲取View可見部分相對于屏幕的坐標
Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
int left = rect.getLeft();
int top = rect.getTop();
int right = rect.getRight();
int bottom = rect.getBottom();
方式六:getLocalVisibleRect()
獲取View可見部分相對于自身View左上角的坐標
Rect rect = new Rect();
view.getLoacalVisibleRect(rect);
int left = rect.getLeft();
int top = rect.getTop();
int right = rect.getRight();
int bottom = rect.getBottom();
注意:getGlobalVisibleRect與getLocalVisibleRect在View完全不可見的情況下返回的Rect實例的坐標為相對屏幕原點的坐標,且當View處在屏幕上方時,top和bottom為負值。
[站外圖片上傳中...(image-f0af2b-1593425845677)]
例子中的tv10和tv9完全不可見,所以其返回的Rect坐標是相對于屏幕原點的坐標。