0

I'm making an Idle Game but now I don't know how to make the listeners of the HUD. It's okay to instantiate an InputListener() in every button of my hud? I have like 20 buttons or actors to touch.

  • I mean, it's the only option? Because i need to access to the variables and functions of the 'button' from the touchDown method from InputListener class (i know i can access but i need to pass parameters, or create a inside class extending InputListener, etc..). It's like a lot of code, imagine 20 buttons instantiating extended InputListener classes, every class with their own code just for one button – El Galactico May 10 '16 at 02:20
  • I don't really understand your issue. It sounds like you have a convoluted setup. The listener only needs to call one method in `touchDown`. You could alternatively assign the same listener to every button and have the `touchDown` method check `event.getListenerActor()` against all your buttons to decide which method to call. If you want your buttons to behave more like the buttons of an OS (cancel press by dragging off of the button and releasing), then use ChangeListener instead of InputListener, and use `changed` instead of `touchDown` to respond to it. – Tenfour04 May 10 '16 at 02:26

2 Answers2

1

Simply use addListener() method for every actor that you want to be clicable. I used to use ClickListener for this purpose although it is sometimes recommended to use ChangeListener due to better behaviour when the button is being disabled.

So what you need to do is just

    Button button;

    //creating button...

    button.addListener(new ClickListener(){
        @Override
        public void clicked(InputEvent event, float x, float y)
        {
            //Do something
        }
    });

and the same for another buttons/actors on your HUD stage.

You can also take a look at this thread where I have asked about performance of many listeners.

m.antkowicz
  • 13,268
  • 18
  • 37
1

Here is a scene2d button, which is really easy to use, I dont understand what the issue is or why you are worried about having a listener on each button or UI object, seems pretty logical to me.

button = new Button(buttonStyle);
    button.setPosition(x, y);
    button.addListener( new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            Gdx.app.log(TAG, "Button clicked");
        };
    });
arnzzz
  • 61
  • 5