Android View获取坐标的方式有很多,这里总结六种,接下来介绍一下每种的区别。

  • getLeft()、getTop()、getRight()、getBottom()
  • getX()、getY()、getRawX()、getRawY()
  • getLocationOnScreen()
  • getLocationInWindow()
  • getGlobalVisibleRect()
  • getLocalVisibleRect()

一.getLeft()、getTop()、getRight()、getBottom():

1.说明:

  • 获取View相对于父View的坐标

2.使用

  • view.getLeft();
    view.getTop();
    view.getRight();
    view.getBottom();

3.图形描述

Android 获取View的坐标位置

  • 获取的view坐标是相对于父布局而言的

二.getX()、getY()、getRawX()、getRawY():

1.说明:

  • 获取点击事件的点击位置相对于其点击控件的坐标,以及相对于屏幕的坐标。

2.使用

  • motionEvent event;

  • event.getX();

  • event.getY();

  • event.getRawX();

  • event.getRawY();

3.图形描述

Android 获取View的坐标位置
三.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.图形描述

Android 获取View的坐标位置
四.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.图形描述

Android 获取View的坐标位置
五.getGlobalVisibleRect():

1.说明:

  • View可见部分 相对于 屏幕的坐标。

2.使用

  • Rect globalRect = new Rect();
    view.getGlobalVisibleRect(globalRect);

  • globalRect.getLeft();
    globalRect.getRight();
    globalRect.getTop();
    globalRect.getBottom();

3.图形描述

Android 获取View的坐标位置
六.getLocalVisibleRect():

1.说明:

  • View可见部分 相对于 自身View位置左上角的坐标。

2.使用

  • Rect localRect = new Rect();
    view.getLocalVisibleRect(localRect);

  • localRect.getLeft();
    localRect.getRight();
    localRect.getTop();
    localRect.getBottom();

3.图形描述

Android 获取View的坐标位置
总结
Android 获取View的坐标位置

相关文章: