方式二的这个方法相当于系统提供的一个对左右、上下移动的API的封装。当计算出偏移量后,只需要使用如下代码就可以完成view的重新布局,效果于使用layout方法一样,代码如下:
//同时对left和right进行偏移 offsetLeftAndRight(offsetX); //同时对top和bottom进行偏移 offsetTopAndBottom(offsetY);这里的offsetX和offsetY于在Layout方法中计算offset的方法一样,这里就不重复了。
完整代码如下:
public class DragView extends TextView { private int lastX; private int lasty; public DragView(Context context) { super(context); initView(); } public DragView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } private void initView() { setBackgroundColor(Color.BLUE); } @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //记录触摸点的坐标 lastX = x; lasty = y; break; case MotionEvent.ACTION_MOVE: //计算偏移量 int offsetX = x - lastX; int offsetY = y - lasty; //同时对left和right进行偏移 offsetLeftAndRight(offsetX); //同时对top和bottom进行偏移 offsetTopAndBottom(offsetY); break; case MotionEvent.ACTION_UP: break; } return true; } }