Click, Press and Release event on Button

Nitesh Kumar picture Nitesh Kumar · Dec 17, 2014 · Viewed 17.4k times · Source

How can I detect clicked, pressed and released states of a Button. I want to perform different functions on these states. On click I want to call function1, on press I want to call function2 and on receive I want to call function3.

We can detect click state using View.OnClickListener. We can detect Pressed and Released states of a Button using View.OnTouchListener and handling ACTION_DOWN and ACTION_UP. I am able to detect these states individually, however, not together.

Below is code for OnCLickListener.

button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            System.out.println(" clicked ");
        }
    });

Below is code for OnTouchListener.

button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    System.out.println(" pressed ");
                    return true;
                case MotionEvent.ACTION_UP:
                    System.out.println(" released ");
                    return true;
            }
            return false;
        }
    });

When I set click and touch listeners on a Button, Click event never gets called. Instead I receive pressed and released state.

How can I handle these three states together?

EDIT:

I added the OnClickListener and OnTouchListener code I have used.

Answer

Pranav Karnik picture Pranav Karnik · Dec 19, 2014

Change the return true; inside case MotionEvent.ACTION_DOWN: and case MotionEvent.ACTION_UP:to return false; or break;