MotionEvent事件-控件随手指拖动 限制控件的滑动位置
private int lastX;
private int lastY;
private int maxRight;
private int maxBottom;
@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:
//得到imageview的父容器
LinearLayout viewParent = (LinearLayout) mImageView.getParent();
if (maxRight == 0) {//这个判断 保证值给max赋值一次
maxRight = viewParent.getRight();
maxBottom = viewParent.getBottom();
}
/**记录控件的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;
//限制left
if (left < 0) {
right += (-left);
left = 0;
}
//限制top
if (top < 0) {
buttom += (-top);
top = 0;
}
//限制right
if (right > maxRight) {
left -= (right - maxRight);
right = maxRight;
}
//限制bottom
if (buttom > maxBottom) {
top -= (buttom - maxBottom);
buttom = maxBottom;
}
mImageView.layout(left, top, right, buttom);
/**再次记录控件的x,y坐标*/
lastX = eventX;
lastY = eventY;
break;
default:
break;
}
return true;/**所有的motionevent都交给imageview来处理*/
}
网友评论