MotionEvent事件-控件随手指拖动
private int lastX;
private int lastY;
@Override
public boolean onTouch(View v, MotionEvent event) {
//getRawX()是控件相对于父容器左上角的距离
//获取控件的x,y坐标
int eventX = (int) event.getRawX();
int eventY = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
/**记录控件的x,y坐标*/
lastX = eventX;
lastY = eventY;
break;
case MotionEvent.ACTION_MOVE:
/**计算偏移量*/
int dx = eventX - lastX;
int dy = eventY - lastY;
/**根据事件的偏移量来移动控件*/
int left = mImageView.getLeft() + dx;
int top = mImageView.getTop() + dy;
int right = mImageView.getRight() + dx;
int buttom = mImageView.getBottom() + dy;
mImageView.layout(left, top, right, buttom);
/**再次记录控件的x,y坐标*/
lastX = eventX;
lastY = eventY;
break;
default:
break;
}
return true;/**所有的motionevent都交给imageview来处理*/
}
网友评论