int startX;
int startY;
int left;
int top;
int[]temp =new int[]{0, 0};
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int x = (int) motionEvent.getRawX();
int y = (int) motionEvent.getRawY();
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:// touch down so check if the
startX = x;
startY = y;
temp[0] = (int) motionEvent.getX();
temp[1] = y - view.getTop();
break;
case MotionEvent.ACTION_MOVE:// touch drag with the ball
left = x -temp[0];
top = y -temp[1];
if (left <0) {//控制左边界不超出
left =0;
}
view.layout(left, top, left + view.getWidth(), top + view.getHeight());//自由拖拽
break;
case MotionEvent.ACTION_UP:
if (Math.abs(x -startX) >2 || Math.abs(y -startY) >2) {//判断是否移动,再一定范围内不算是移动,解决触发事件冲突
//将最后拖拽的位置定下来,否则页面刷新渲染后按钮会自动回到初始位置
//注意父容器
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view.getLayoutParams();
lp.setMargins(left, top, 0, 0);
view.setLayoutParams(lp);
//确定是拖拽
// isMove = true;
}
break;
}
return true;
}