这个view所在布局是一个LinearLayout,写好布局文件后,直接拖动就可以看到实现效果
public class DragView extends View {
private int lastX;
private int lastY;
public DragView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public DragView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public DragView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// 获取当前触摸的绝对坐标
int rawX = (int) event.getRawX();
int rawY = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 上一次离开时的坐标
lastX = rawX;
lastY = rawY;
break;
case MotionEvent.ACTION_MOVE:
// 两次的偏移量
int offsetX = rawX - lastX;
int offsetY = rawY - lastY;
moveView(offsetX, offsetY);
// 不断修改上次移动完成后坐标
lastX = rawX;
lastY = rawY;
break;
default:
break;
}
return true;
}
private void moveView(int offsetX, int offsetY) {
// 方法一
// layout(getLeft() + offsetX, getTop() + offsetY, getRight() +
// offsetX, getBottom() + offsetY);
// 方法二
// offsetLeftAndRight(offsetX);
// offsetTopAndBottom(offsetY);
// 方法三
// LinearLayout.LayoutParams layoutParams = (LayoutParams)
// getLayoutParams();
// layoutParams.leftMargin = getLeft() + offsetX;
// layoutParams.topMargin = getTop() + offsetY;
// setLayoutParams(layoutParams);
// 方法四
// ViewGroup.MarginLayoutParams layoutParams = (MarginLayoutParams)
// getLayoutParams();
// layoutParams.leftMargin = getLeft() + offsetX;
// layoutParams.topMargin = getLeft() + offsetY;
// setLayoutParams(layoutParams);
// 方法五
((View) getParent()).scrollBy(-offsetX, -offsetY);
}
}