How to detect when button pressed and released on android

Andy Thompson picture Andy Thompson · Aug 15, 2012 · Viewed 46.9k times · Source

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

Answer

Nick picture Nick · Aug 15, 2012

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;
     }
  });