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?
setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface.
In Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it.
Difference Between OnClickListener vs OnClick: * OnClickListener is the interface you need to implement and can be set to a view in java code. * OnClickListener is what waits for someone to actually click, onclick determines what happens when someone clicks.
Callback function of button is called automatically.
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(); } } };
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(); } } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With