Capture button release in Android

2020-01-29 08:49发布

问题:

Is it possible to capture release of a button just as we capture click using onClickListener() and OnClick() ?

I want to increase size of a button when it is pressed and move it back to the original size when the click is released. Can anyone help me how to do this?

回答1:

You should set an OnTouchListener on your button.

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            increaseSize();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            resetSize();
        }
    }
};


回答2:

You have to handle MotionEvent.ACTION_CANCEL as well. So the code will be:

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP || 
            event.getAction() == MotionEvent.ACTION_CANCEL) {
            increaseSize();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            resetSize();
        }
    }
};


回答3:

use an OnTouchListener or OnKeyListener instead.



回答4:

You might be able to do this by overriding the onKeyDown and onKeyUp. These are both inherited from android.widget.TextView. Please see the android.widget.Button doc for (a bit) more info.



回答5:

Eric Nordvik has the right answer except that

event.getAction() == MotionEvent.ACTION_UP

never got executed for me. Instead I did implement

    button.setOnClickListener(new OnClickListener() {
        @Override
        public boolean onClick(View v) {
            resetSize();      
    }
};

for the touch ACTION_UP.