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應該返回它是否處理事件,而不是您的個人計時器的狀態。