It is right that using setPressed(true)
does not keep the button which is being clicked in the pressed state, because after the click the button returns to setPressed(false)
.
You can override onTouch
and implement your own behaviour, like this:
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//this is touch
v.setPressed(true);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
//this is click. Do everything triggered by a click here
deselectAllButtons();
v.setPressed(true);
}
return true;
}
});
In deselectAllButtons()
I set all my buttons' pressed states to false
.
Note that the key idea here is that onClick should not be invoked. That's why onTouch should return true, meaning that the touch event is consumed:
onTouch() - This returns a boolean to indicate whether your listener
consumes this event. The important thing is that this event can have
multiple actions that follow each other. So, if you return false when
the down action event is received, you indicate that you have not
consumed the event and are also not interested in subsequent actions
from this event. Thus, you will not be called for any other actions
within the event, such as a finger gesture, or the eventual up action
event.