28

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

Andy Thompson
  • 299
  • 1
  • 3
  • 9

3 Answers3

49

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;
     }
  });
Blue Bot
  • 2,278
  • 5
  • 23
  • 33
Nick
  • 8,181
  • 4
  • 38
  • 63
  • Unfortunately, this does not work when the button is pressed with the keyboard. It only works when it is touched. – Rémi Aug 26 '12 at 21:57
  • So you are wanting to see how long a keyboard button is pressed? – Nick Aug 27 '12 at 01:38
  • 3
    This aproach needs to be modifed. If you press then slide your finger holding the button in a press state then release the finger the button stays pressed. You need also add `MotionEvent.ACTION_CANCEL` to handle that kind of behaviour. – Bob Oct 01 '16 at 10:12
  • also missing `return true` at the end of `onTouch` method – Blue Bot Nov 15 '17 at 16:49
7

This will definitely work:

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            increaseSize();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            resetSize();
        }
        return true;
    }
});
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
Pramod J George
  • 1,723
  • 12
  • 24
5
  1. In onTouchListener start the timer.
  2. In onClickListener stop the times.

calculate the differece.

Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226