触控拖动屏幕事件一般情况下是重载onTouchEvent函数 实现方法如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/**mainView的坐标*/
private float x, y;
/**触屏事件处理*/
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
this.x = x;
this.y = y;
case MotionEvent.ACTION_MOVE:
mainView.layout((int)(x - this.x), (int)(y - this.y), (int)(x + mainView.getWidth()
- this.x), (int)(y - this.y + mainView.getHeight()));
break;
case MotionEvent.ACTION_UP:
if((Math.abs(this.y - y) < 10))
{
if(x - this.x > 30)
{
MessageBox("向右移动");
}else if(x - this.x < -30)
{
MessageBox("向左移动");
}
}
break;
}
mainView.postInvalidate();
return super.onTouchEvent(event);
}
处理控件拖动事件跟上边类似 可添加一个OnTouchListener到控件上
下边展示一个对Button按钮的拖动
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
final Button btn = (Button) findViewById(R.id.btn_hello);
btn.setOnTouchListener(new OnTouchListener() {
int[] temp = new int[] { 0, 0 };
public boolean onTouch(View v, MotionEvent event) {
int eventaction = event.getAction();
Log.i("&&&", "onTouchEvent:" + eventaction);
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch (eventaction) {
case MotionEvent.ACTION_DOWN: // touch down so check if the
temp[0] = (int) event.getX();
temp[1] = y - v.getTop();
break;
case MotionEvent.ACTION_MOVE: // touch drag with the ball
v.layout(x - temp[0], y - temp[1], x + v.getWidth()
- temp[0], y - temp[1] + v.getHeight());
v.postInvalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
拖动事件主要就是在touch事件的envent中处理按下 移动 和 松开