How to detect when button pressed and released on android How to detect when button pressed and released on android android android

How to detect when button pressed and released on android


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


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.