Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click, Press and Release event on Button

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.

like image 1000
Nitesh Kumar Avatar asked Dec 17 '14 07:12

Nitesh Kumar


2 Answers

Easy since Button is a View:

    button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // Pressed
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                // Released
            }
            return true;
        }
    });
like image 181
MineConsulting SRL Avatar answered Nov 20 '22 15:11

MineConsulting SRL


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

like image 5
Pranav Karnik Avatar answered Nov 20 '22 13:11

Pranav Karnik