How to detect when button pressed and released on android
Asked Answered
K

3

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

Kilah answered 15/8, 2012 at 3:29 Comment(1)
L
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;
     }
  });
Lewandowski answered 15/8, 2012 at 4:23 Comment(4)
Unfortunately, this does not work when the button is pressed with the keyboard. It only works when it is touched.Coronary
So you are wanting to see how long a keyboard button is pressed?Lewandowski
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.Quinacrine
also missing return true at the end of onTouch methodHolpen
J
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;
    }
});
Jeweljeweler answered 15/8, 2012 at 5:41 Comment(0)
C
5
  1. In onTouchListener start the timer.
  2. In onClickListener stop the times.

calculate the differece.

Cleocleobulus answered 15/8, 2012 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.