目录
一、坐标系
Android系统中有两种坐标系,分别为Android坐标系和View坐标系。
1、Android坐标系
左上角为(0,0),右为x轴正方向,下为y轴正方向
2、View坐标系
1)View自身的坐标
通过如下方法获得View到其父控件(ViewGroup)的距离。
- getTop()
View自身顶边到其父布局顶边的距离。 - getLeft()
View自身左边到其父布局左边的距离。 - getRight()
View自身右边到其父布局左边的距离。 - getBottom()
View自身底边到其父布局顶边的距离。
2)MotionEvent提供的方法
上图中间的那个圆点假设就是我们触摸的点。
无论是View还是ViewGroup,最终的点击事件都会由onTouchEvent(MotionEvent event)方法来处理。
MotionEvent也提供了获取焦点坐标的各种方法。
- getX()
点击事件距离控件左边的距离。 - getY()
点击事件距离控件顶边的距离。 - getRawX()
点击事件距离整个屏幕左边的距离。 - getRawY()
点击事件距离整个屏幕顶边的距离。
二、View的滑动
不管是哪种滑动方式,其基本思想都是类似的:当点击事件传到View时,系统记下触摸点的坐标,手指移动时系统记下移动后触摸的坐标并算出偏移量,并通过偏移量来修改View的坐标。
实现View滑动有很多种方法,这里主要讲解以下几种滑动方法。
1、layout(int l, int t, int r, int b)
l:View自身左边到其父布局左边的距离
t:View自身顶边到其父布局顶边的距离
r:View自身右边到其父布局左边的距离
b:View自身底边到其父布局顶边的距离
public class LayoutView extends View {
private int lastX;
private int lastY;
public LayoutView(Context context) {
super(context);
}
public LayoutView(Context context, @Nullable AttributeSet attrs) {
super(con