Question

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

Was it helpful?

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

OTHER TIPS

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;
    }
});
  1. In onTouchListener start the timer.
  2. In onClickListener stop the times.

calculate the differece.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top