[英]CountDownTimer not cancelled on MotionEvent.ACTION_UP after starting it in ACTION_DOWN
我知道onLongTouchListener不存在,所以我正在尝试制作自己的版本,因为我真的需要触摸坐标,所以不能使用onLongClickListener。 我的代码如下:
touchImageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, final MotionEvent motionEvent) {
CountDownTimer counter = new CountDownTimer(500, 1) {
public void onTick(long millisUntilFinished) {
System.out.println("REMAINING: "+(millisUntilFinished));
}
public void onFinish() {
System.out.println("IT'S OVER");
}
};
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN){
counter.start();
} else if( motionEvent.getAction() == MotionEvent.ACTION_UP){
counter.cancel();
}
return true;
}
});
问题是:当我将手指放在屏幕上时,计数器开始计数,但是按我的预期抬起手指并没有取消计数:
else if( motionEvent.getAction() == MotionEvent.ACTION_UP){
counter.cancel();
}
你们能帮我吗?
编辑:
遵循评论和答案后,它现在可以工作:
final CountDownTimer counter;
counter = new CountDownTimer(500,1) {
@Override
public void onTick(long l) {
System.out.println("REMAINING "+l);
}
@Override
public void onFinish() {
System.out.println("IT'S OVER");
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE));
}
}
};
touchImageView.setOnTouchListener(new View.OnTouchListener() {
CountDownTimer c = counter;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN){
c.start();
}
if (motionEvent.getAction() == MotionEvent.ACTION_UP){
c.cancel();
}
return true;
}
});
发生这种情况是因为您没有取消相同的计数器。 onTouch
触发onTouch
时( ACTION_DOWN
),您将构造一个计数器并启动它。 当第二次触发onTouch
( ACTION_UP
)时,您将构造一个新计数器并将其取消。 您正在启动一个计数器并取消一个完全不同的计数器。
您将需要在onTouch
侦听器之外维护一个计数器,或者确保您确实以其他方式取消了正确的计数器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.