View 及ViewGroup

在Android中,常用控件可大致分为两大类:ViewViewGroupViewGroup可包含多个ViewViewGroup,形成一个树状结构。需要注意的是ViewGroup也继承自View。View及ViewGroup组织结构如下:

坐标系

在Android中有两种坐标系:Android坐标系和View坐标系。了解坐标系是对View进行更多操作的基础。

Android坐标系

以屏幕左上角为原点,原点向右为X轴正方向,原点向下为Y轴正方向。在触控事件中,getRawX()getRawY()获取的坐标也是Android坐标系的坐标。

View坐标系

View坐标系是以View为基础的坐标系,搞清楚下图的关系也就清楚了View坐标系。

下面解释一下上图中涉及到的各个方法。
其中下面4个方法可在View中直接获取:

  • getTop():获取View顶边到父View顶边的距离
  • getBottom():获取View底边到父View顶边的距离
  • getLeft():获取View左边到父View左边的距离
  • getRight():获取View右边到父View左边的距离

剩余4个方法需要在View有触摸事件发生时,通过onTouchEvent(MotionEvent event)方法中的event获取:

  • getX():触摸点到View左边的距离
  • getY():触摸点到View顶边的距离
  • getRawX():触摸点到屏幕左边的距离
  • getRawY():触摸点到屏幕顶边的距离

示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MyView extends View {
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}

int top = getTop();
int bottom = getBottom();
int left = getLeft();
int right = getRight();

@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
float rawX = event.getRawX();
float rawY = event.getRawY();
return super.onTouchEvent(event);
}
}

源码见Github

参考文献:
《Android进阶之光》
《Android开发艺术探索》

关注我