0

我有一个计时器,我想在按住按钮时启动,并在我放开时重置计时器。这可能与onClick,但我真的不知道如何在这个项目中使用onTouch事件。第一个代码片段工作,但如何实现触摸,而不是按照asy的方式点击?在我的timerproject中实现onTouch事件

@Override 

    public void onClick(View v) 
     { 
      if (!timerHasStarted) 
       { 
        countDownTimer.start(); 
        timerHasStarted = true; 
        startB.setText("Start"); 

       } 
      else 
       { 

        countDownTimer.cancel(); 
        timerHasStarted = false; 
        startB.setText("RESET"); 
       } 
     } 

 public boolean onTouch(View v, MotionEvent event) { 

     final float mouseSensitivity = 0.5f; 

     if(event.getAction()==MotionEvent.ACTION_DOWN){ 
      countDownTimer.start(); 
      timerHasStarted = true; 
     } else if(event.getAction()==MotionEvent.ACTION_UP){ 
      countDownTimer.cancel(); 
      timerHasStarted = false; 


     } 
     return timerHasStarted; } } 

public void onTouch(View v, MotionEvent event) { 

     // final float mouseSensitivity = 0.5f; 

     if(event.getAction()==MotionEvent.ACTION_DOWN){ 
      countDownTimer.start(); 
      timerHasStarted = true; 
     } else if(event.getAction()==MotionEvent.ACTION_UP){ 
      countDownTimer.cancel(); 
      timerHasStarted = false; 


     } 
    } 

回答

0

确保您通过addind @Override批注覆盖onTouch,第二执行肯定不会,因为onTouch总是返回boolean值。

确保您接触到电话而没有其他人。设置视图的onTouchListener到对象,或用自己的类扩展的查看和执行的onTouchEvent

考虑,如果你需要检查的观点实际上是在提到按钮

也处理MotionEvent.CANCEL,作为偶尔会发生,你可能想要做点什么。 MotionEvent.MOVE可以被跳过,因为当这种情况发生时你不想做任何事情。

onTouch应该返回它是否处理事件,而不是您的个人计时器的状态。