listener for pressing and releasing a button

前端 未结 3 489
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 01:29

How can I listen for when a Button is pressed and released?

相关标签:
3条回答
  • 2020-12-24 01:45

    The answer given by fiddler is correct for generic views.

    For a Button, you should return false from the touch handler always:

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

    If you return true you will circumvent the button's regular touch processing. Which means you will loose the visual effects of pressing the button down and the touch ripple. Also, Button#isPressed() will return false while the button is actually pressed.

    The button's regular touch processing will ensure that you get the follow-up events even when returning false.

    0 讨论(0)
  • 2020-12-24 01:45

    onTouchListener is what you are looking for.

    You will need to use the correct MotionEvent.

    This will allow you to handle the different types of "touches".

    0 讨论(0)
  • 2020-12-24 01:54

    You can use a onTouchListener:

    view.setOnTouchListener(new View.OnTouchListener() {        
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // PRESSED
                    return true; // if you want to handle the touch event
                case MotionEvent.ACTION_UP:
                    // RELEASED
                    return true; // if you want to handle the touch event
            }
            return false;
        }
    });
    
    0 讨论(0)
提交回复
热议问题