javaandroidbuttontimerpressed

How to detect when button pressed and released on android


I would like to start a timer that begins when a button is first pressed and ends when it is released (basically I want to measure how long a button is held down). I'll be using the System.nanoTime() method at both of those times, then subtract the initial number from the final one to get a measurement for the time elapsed while the button was held down.

(If you have any suggestions for using something other than nanoTime() or some other way of measuring how long a button is held down, I'm open to those as well.)

Thanks! Andy


Solution

  • Use OnTouchListener instead of OnClickListener:

    // this goes somewhere in your class:
      long lastDown;
      long lastDuration;
    
      ...
    
      // this goes wherever you setup your button listener:
      button.setOnTouchListener(new OnTouchListener() {
         @Override
         public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN) {
               lastDown = System.currentTimeMillis();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
               lastDuration = System.currentTimeMillis() - lastDown;
            }
    
            return true;
         }
      });