Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture button release in Android

Tags:

android

button

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?

like image 751
mdv Avatar asked Sep 24 '10 05:09

mdv


People also ask

What is the use of setOnClickListener in Android?

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.

Is Button a view in Android?

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.

What is the difference between OnClick and OnClickListener?

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.

Which callback is called when a button is tapped?

Callback function of button is called automatically.


2 Answers

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();         }     } }; 
like image 154
Eric Nordvik Avatar answered Sep 30 '22 07:09

Eric Nordvik


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();         }     } }; 
like image 44
icastell Avatar answered Sep 30 '22 09:09

icastell