I have a button on screen, and I want the user to be able to dismiss it by either clicking on it, or hitting space. The button is constructed as follows:
button = new TextButton("RESUME", skin);
button.setVisible(false);
button.addListener(new InputListener(){
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
return true;
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
button.addAction(
Actions.sequence(
// send out of the screen
Actions.moveTo(WORLD_WIDTH / 2 - button.getWidth() / 2, -button.getHeight(), 0.2f),
Actions.hide(),
Actions.run( () -> {
resumeGame();
}),
Actions.removeActor()
)
);
}
});
...
table.add(button);
stage.AddActor(table);
...
So if I make the button appear and click on it, everything is fine. I can repeat the sequence "button appear/click" at will, and each time the button will move offscreen to the bottom and will be removed from the table. I want the button to do exactly the same when the user hits space, so I did:
private void clickButton(TextButton button){
InputEvent inputEvent = new InputEvent();
inputEvent.setRelatedActor(button);
inputEvent.setType(InputEvent.Type.touchDown);
button.fire(inputEvent);
inputEvent.setType(InputEvent.Type.touchUp);
button.fire(inputEvent);
}
// then:
stage.addListener(new InputListener(){
@Override
public boolean keyDown(InputEvent event, int keycode) {
if (keycode == Input.Keys.SPACE){
clickButton(button);
return true;
}
}
Now when the button is shown and I hit space, it looks like it works, but if I make the button appear again, it's shown briefly then it disappears (it's removed from the table). It's like the final Actions.removeActor() in the button listener is not executed when the button is "clicked" using space, and it's then executed the next time when the button appears again, making it disappear immediately.
EDIT: this is indeed the case. I put a debug print statement right before the Actions.removeActor() action, and upon mouse click the text is printed, but using clickButton() it's not (and it's printed instead when the button is shown again and readded to the table).
Am I doing something wrong here? What's the "correct" way to click a button programmatically (yes, I've already seen https://stackoverflow.com/questions/25870645/programatically-perform-click-on-actor-libgdx)
Actions.removeActor()
to beforeActions.hide()
. Otherwise see my answer for another possible solution. \$\endgroup\$ – Charanor Jul 28 '17 at 13:30InputListener
and theChangeListener
:) Then it should catch both just fine. \$\endgroup\$ – Charanor Jul 28 '17 at 14:10