Search code examples
androidbuttononclickonlongclicklistener

Android to detect when you are holding down a button


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
}

Solution

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