Reputation: 5440
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.
Upvotes: 11
Views: 23878
Reputation: 2340
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;
}
});
Upvotes: 13
Reputation: 3388
Change the return true;
inside case MotionEvent.ACTION_DOWN:
and case MotionEvent.ACTION_UP:
to return false;
or break;
Upvotes: 5
Reputation: 3204
See this link.
You can handle click manually in MotionEvent.ACTION_UP
event by
button.performClick();
Upvotes: 0
Reputation: 61
clicked event include pressed and released state,if you want to fire clicked event,put method after ACTION_UP
Upvotes: -1