nic*_*amp 0 java android touchimageview
我知道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;
}
});
Run Code Online (Sandbox Code Playgroud)
问题是:当我将手指放在屏幕上时,计数器开始计数,但是按我的预期抬起手指并没有取消计数:
else if( motionEvent.getAction() == MotionEvent.ACTION_UP){
counter.cancel();
}
Run Code Online (Sandbox Code Playgroud)
你们能帮我吗?
编辑:
遵循评论和答案后,它现在可以工作:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
小智 6
发生这种情况是因为您没有取消相同的计数器。当onTouch被触发第一次(ACTION_DOWN),构造一个计数器并启动它。当onTouch被触发,第二次(ACTION_UP),构造一个新的计数器,并取消它。您正在启动一个计数器并取消一个完全不同的计数器。
您将需要在侦听器外部维护一个计数器,onTouch或者确保您确实以其他方式取消了正确的计数器。
| 归档时间: |
|
| 查看次数: |
41 次 |
| 最近记录: |