1.重写ontouchlistener
class MyOnTouch implements OnTouchListener {
int[] temp = new int[] { 0, 0 };
Boolean ismove = false;
int downX = 0;
int downY = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
int eventaction = event.getAction();
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();
downX = (int) event.getRawX();
downY = (int) event.getRawY();
ismove = false;
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());
if (Math.abs(downX - x) > 10 || Math.abs(downY - y) > 10)
ismove = true;
break;
case MotionEvent.ACTION_UP:
if (!ismove)
Toast.makeText(MainActivity.this, "点击了这个按钮",
Toast.LENGTH_LONG).show();
break;
}
return false;
}
}
对于点击事件了,当然也可以用手势事件来解决 代码如下:
class MyGesture implements OnTouchListener, OnGestureListener {
GestureDetector myGesture = new GestureDetector(MainActivity.this, this);
View view = null;
int[] temp = new int[] { 0, 0 };
@Override
public boolean onTouch(View v, MotionEvent event) {
// 这一步只是我的强迫症而已,因为onTouch事件是不断被调用的
if (view == null)
view = v;
myGesture.onTouchEvent(event);
return false;
}
// 在按下时调用
@Override
public boolean onDown(MotionEvent e) {
temp[0] = (int) e.getX();
temp[1] = ((int) e.getRawY()) - view.getTop();
return false;
}
// 手指在触摸屏上迅速移动,并松开的动作。
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false;
}
// 长按的时候调用
@Override
public void onLongPress(MotionEvent e) {
}
// 按住然后滑动时调用
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
int x = (int) e2.getRawX();
int y = (int) e2.getRawY();
view.layout(x - temp[0], y - temp[1],
x + view.getWidth() - temp[0],
y - temp[1] + view.getHeight());
return false;
}
// 用户轻触触摸屏,尚未松开或拖动,由一个1个MotionEvent ACTION_DOWN触发
// 注意和onDown()的区别,强调的是没有松开或者拖动的状态
@Override
public void onShowPress(MotionEvent e) {
}
// 用户(轻触触摸屏后)松开,由一个1个MotionEvent ACTION_UP触发
@Override
public boolean onSingleTapUp(MotionEvent e) {
Toast.makeText(MainActivity.this, "点击了按钮", Toast.LENGTH_LONG)
.show();
return false;
}
}
最后添加事件就可以了:
touchButton.setOnTouchListener(new MyOnTouch());
最主要的是这句话 对于按钮的位置进行了重绘:
v.layout(x - temp[0], y - temp[1], x + v.getWidth() - temp[0],
y - temp[1] + v.getHeight());