[英]Android - Receiving wrong touch events
Here is the code I am using: 这是我正在使用的代码:
// Handling Touch Events
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float onOffBitmapWidth = this.onOffBitmap.getWidth();
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
if (this.touchMove) {
if (togglePositionX > this.onOffBitmap.getWidth() / 4.0f) {
togglePositionX = this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f;
} else if (togglePositionX <= this.onOffBitmap.getWidth() / 4.0f) {
togglePositionX = 0.0f;
}
this.invalidate();
this.touchMove = false;
return true;
} else {
return false;
}
} else if (motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
this.touchMove = false;
this.invalidate();
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
this.touchMove = true;
float currentX = motionEvent.getX();
if (currentX > 0.0f && currentX < (this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f)) {
togglePositionX = currentX;
} else if (currentX >= (this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f)) {
togglePositionX = this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f;
} else if (currentX <= 0.0f) {
togglePositionX = 0.0f;
}
this.invalidate();
return true;
}
return true;
}
@Override
public void onClick(View v) {
if (togglePositionX == 0.0f) {
togglePositionX = this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f;
} else {
togglePositionX = 0.0f;
}
this.invalidate();
}
I am using onClick event for single tap event. 我将onClick事件用于单击事件。 The problem is that ACTION_MOVE is called even if I only tap the screen.
问题是,即使我只点击屏幕,也会调用ACTION_MOVE。 I even do it in a funny way (with the very tip of my finger).
我什至以一种有趣的方式做到了(用我的指尖)。
I end up using an array list containing the history of touch positions that the user performs on the view + a flag to detect wether it's a real ACTION_MOVE or not. 我最终使用了一个数组列表,其中包含用户在视图上执行的触摸位置的历史记录以及一个用于检测是否为实际ACTION_MOVE的标志。 Here is the code that I implemented inside
if (motionEvent.getAction() == MotionEvent.ACTION_MOVE)
这是我在
if (motionEvent.getAction() == MotionEvent.ACTION_MOVE)
内实现的代码
float currentX = motionEvent.getX();
this.userTouchMoveArray.add(currentX);
if (this.userTouchMoveArray.size() == 1) {
touchIsMoved = false;
} else {
float oldestX = userTouchMoveArray.get(0);
if (Math.abs(currentX - oldestX) > 2.0f) {
touchIsMoved = true;
} else {
touchIsMoved = false;
}
}
Working like a charm. 像魅力一样工作。 (You can define your own tolerance, here I am using 2 px)
(您可以定义自己的公差,这里我使用2像素)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.