我知道 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;
}
});