我想计算屏幕上触摸位置的增量。为此,我使用了这段代码:
public boolean onTouchEvent(MotionEvent event) {
touchX = (int) event.getX();
touchY = (int) event.getY();
deltaX = touchX - oldX;
deltaY = touchY - oldY;
oldX = touchX;
oldY = touchY;
return super.onTouchEvent(event);
}
现在,当我在屏幕上移动手指一段时间后,我得到了正确的增量。但是当我停下手指但是不要抬起它时会出现问题。那时,我只得到最后一帧的非零增量。这是因为当手指在屏幕上而不是静态时,不会调用onTouchEvent
。当手指静止时,我应该得到零增量。
这个问题的解决方案是什么?
答案 0 :(得分:1)
手指在屏幕上停留不 a MotionEvent
,因此不会调用此方法。
试试这个。
private Handler mHandler = new Handler();
private static final int FINGER_STOP_THRESHOLD = 500;
public boolean onTouchEvent(MotionEvent event) {
touchX = (int) event.getX();
touchY = (int) event.getY();
deltaX = touchX - oldX;
deltaY = touchY - oldY;
oldX = touchX;
oldY = touchY;
mHandler.removeCallbacksAndMessages(null);
if(event.getActionMasked() != MotionEvent.ACTION_UP){
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
deltaX = 0;
deltaY = 0;
}
}, FINGER_STOP_THRESHOLD);
}
return super.onTouchEvent(event);
}
您可以将FINGER_STOP_THRESHOLD
更改为您想要的值。
答案 1 :(得分:0)
使用此代码,所有内容都会在该代码上加上注释:
Double x;//Using double, so I can assign null to this, when touch is removed
Double y;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getAction() & MotionEvent.ACTION_MASK;
if (action == MotionEvent.ACTION_DOWN) {
x=Double.valueOf(motionEvent.getX());//On touch, set initial position
y=Double.valueOf(motionEvent.getY());
}
if (action == MotionEvent.ACTION_UP) {
x= null;//On touch removed, set it to null
y=null;
}
if (action == MotionEvent.ACTION_MOVE) {
Log.d("d--diff", (x-motionEvent.getX()) + " - " + (y-motionEvent.getY()));
//Calculate difference
}
return true;
}
如有任何疑问,请随时询问。