1
\$\begingroup\$

I created a button and assigned an input listener in the resize() method of the screen.

For simplicity's sake, whenever I press the button, 1000 adds to a total amount. The weird part is, it adds 2000 when I press the button. Then I moved the button's input listener addition to the constructor - now it works perfectly adding 1000.

For some odd reason, if I set the input handler in the resize method it somehow does everything it is supposed to twice. The game works when I transfer that piece of code to the constructor, but why on earth did it do the assigned thing twice?

This is the code I use for attaching the input listener:

button.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int   pointer, int button) {
                return true;
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                count += increment;
                countLabel.setText(String.valueOf(count));
        }
    });
\$\endgroup\$
1
\$\begingroup\$

For some odd reason, if I set the input handler in the resize method it somehow does everything it is supposed to twice. The game works when I transfer that piece of code to the constructor, but why on earth did it do the assigned thing twice?

If the Resize event gets called multiple times, you will add your event handler for each time it's called. Event handlers can be added multiple times, and they will run once for each time they're added. Your event handler worked fine, the problem is just that your handler was called more than once.

When you moved it to the constructor, you moved it to a place that would only ever be called once, so that worked just fine.

If the Resize event was ever called a third time, clicking the button would run the handler three times, incrementing the value that many times. I haven't used libgdx, but if this would occur when the phone orientation changes, you should definitely not be putting listeners like this in the Resize event.

Majd's answer explains why the Resize method would be called twice. Seems like it's safer to place those listeners elsewhere - like you have done.

\$\endgroup\$
1
\$\begingroup\$

This is a well known (feature) that has to do with the way Android reports the screen size. It seems to do it once for the wrong orientation and once for the correctone. I've seen some people have success by locking the orientation in the manifest. Here are some forum posts on this topic:

Libgdx forum post 1

Libgdx forum post 2

Libgdx forum post 3

Libgdx forum post 4

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.