这是我正在使用的代码:
// 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();
}
我将 onClick 事件用于单击事件。问题是即使我只点击屏幕也会调用 ACTION_MOVE。我什至以一种有趣的方式(用我的指尖)来做这件事。