Exciter

生命不息、折腾不止

0%

Android View 01-坐标系

1 View层级关系

2 坐标系

2.1 Android坐标系
2.2 视图坐标系
2.2.1 View自身宽高

方法说明:

  • getWidth() 获取View自身宽度
  • getHeight() 获取View自身高度
    示例代码:
    1
    2
    3
    4
    5
    6
    7
    mTvView.post(() -> {
    Log.d(TAG, "View getWidth: " + mTvView.getWidth();
    Log.d(TAG, "View getHeight: " + mTvView.getHeigh();
    });
    //打印结果
    2021-04-07 11:06:49.775 30821-30821/com.exciter.view D/View01Activity: View getWidth: 600
    2021-04-07 11:06:49.775 30821-30821/com.exciter.view D/View01Activity: View getHeight: 600
    2.2.2 View自身坐标
    方法说明:
  • getLeft() View自身左边到父布局左边的距离
  • getTop() View自身顶部到父布局顶部的距离
  • getRight() View自身右边到父布局右边的距离
  • getBottom() View自身底部到父布局底部的距离
    示例代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     mTvView.post(() -> {
    Log.d(TAG, "View getLeft: " + mTvView.getLeft());
    Log.d(TAG, "View getTop: " + mTvView.getTop());
    Log.d(TAG, "View getRight: " + mTvView.getRight());
    Log.d(TAG, "View getBottom: " + mTvView.getBottom());
    });
    //打印结果
    2021-04-07 11:06:49.775 30821-30821/com.exciter.view D/View01Activity: View getLeft: 150
    2021-04-07 11:06:49.775 30821-30821/com.exciter.view D/View01Activity: View getTop: 300
    2021-04-07 11:06:49.775 30821-30821/com.exciter.view D/View01Activity: View getRight: 750
    2021-04-07 11:06:49.775 30821-30821/com.exciter.view D/View01Activity: View getBottom: 900
2.2.3 触摸点坐标

View和ViewGroup触摸2021年4月7日11:25:01最终都由onTouchEvent(MotionEvent event)来处理,MotionEvent提供了获取坐标点的方法。


方法说明:

  • getX() 获取触摸点距离控件左边的距离,也就是X轴视图坐标
  • getY() 获取触摸点距离控件顶部的距离,也就是Y轴视图坐标
  • getRawX() 获取触摸点距离屏幕左边的距离,也就是X轴绝对坐标
  • getRawY() 获取触摸点距离屏幕顶部的距离,也就是Y轴绝对坐标
    示例代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     mTvView.setOnTouchListener((v, event) -> {
    Log.d(TAG, "View getX: " + event.getX());
    Log.d(TAG, "View getY: " + event.getY());
    Log.d(TAG, "View getRawX: " + event.getRawX());
    Log.d(TAG, "View getRawY: " + event.getRawY());
    return false;
    });
    //打印结果
    2021-04-07 11:29:01.167 30821-30821/com.exciter.view D/View01Activity: View getX: 320.0
    2021-04-07 11:29:01.167 30821-30821/com.exciter.view D/View01Activity: View getY: 336.0
    2021-04-07 11:29:01.167 30821-30821/com.exciter.view D/View01Activity: View getRawX: 515.0
    2021-04-07 11:29:01.167 30821-30821/com.exciter.view D/View01Activity: View getRawY: 915.0