Android to detect when you are holding down a button

The Tokenizer picture The Tokenizer · Jul 30, 2012 · Viewed 8k times · Source

I need to be able to tell when the user is holding a button down and when the user lets go. This is different from onClickListener and onLongClickListener. How would i go about doing something like this?

For example I press a button that starts a chronometer.(pseudo code)

if ButtonIsBeingPressed
{
chronometer start(); //and keep going
}
else chronometer stop();
//or on release or something
}

Answer

Sam picture Sam · Jul 30, 2012

Look into the OnTouchListener it has MotionEvents for Down (press) and Up (release):

view.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // Start
            break;
        case MotionEvent.ACTION_UP:
            // End
            break;
        }
        return false;
    }
});