Scene2d Listeners via Lambda
See original GitHub issueIssue details
Currently LibGDX listeners in scene2d are always added via the addListener(...)
method which takes a generic EventListener interface object. If you want to listen for a specific event you always have to implement an abstract listener class like ChangeListener
, ClickListener
, etc…
This creates a lot of boilerpalte code like
startGameButton.addListener( new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
// code comes here
}
});
even for simple click listeners. It is not possible to use lambda methods/method references here which is really annoying (a bit like Java Swing was before Lambda methods were introduced in Java 8). If there were specific addClickListener( ButtonClickListener ) methods then the above code could be written in a single line (ignoring x, y) using lambda notation:
startGameButton.addClickListener( () -> ... );
This could easily be implemented on top of the current implementation via simple wrapper classes/methods like:
public interface ButtonClickListener { ... }
and in button classes:
public void addClickListener( final ButtonClickListener listener ) {
addListener( new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
listener.onClick();
}
};
)
`
Alternatively one could also migrate ClickListener to an interface with default methods. But since you try to keep Java 8 of LibGDX core the first way is probably better for now.
Please select the affected platforms
- Android
- iOS
- HTML/GWT
- Windows
- Linux
- MacOS
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:8 (5 by maintainers)
Top GitHub Comments
I use this in my app code:
With a static import it allows eg:
I don’t usually need the parameters, but it could be done with an interface other than Runnable.
It doesn’t feel great to have many
addXxxListener
methods solely for lambdas. WouldaddClickListener
go on Actor? What aboutaddChangeListener
? I’m not sure Actor should really know about ChangeListener. Likely there are other listener types that definitely don’t belong on Actor, in which case we are sprinklingaddXxxListener
methods all over. It’s not the worst thing in the world, I’m just not sure we should go down that road. The static import solution above is almost as good, with the mess centralized (in app code, currently).looks familiar to me 😄 here’s my contribution, for what it worth :