Search code examples
libgdximagebutton

LibGdx ImageButton playing sound


I have created an imageButton with three drawable images; one is button-up,button-down and button checked.Its purpose is to ON and OFF sound for the game.once sound is OFF,checked image should be displayed.

I have written the code like this:

soundButton = new ImageButton(new TextureRegionDrawable(soundTexture1),
            new TextureRegionDrawable(soundTexture2), new TextureRegionDrawable(soundTexture3));
    stage.addActor(soundButton);

    soundButton.setPosition(Constants.WORLD_WIDTH / 4 + 300f, Constants.WORLD_HEIGHT / 4, Align.bottomLeft);
soundButton.addListener(new ChangeListener(){
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            if(!game.soundBool)
                game.soundBool=true;
                else
                    game.soundBool=false;
        }
    });

Here soundBool is initially false and game sounds will play when it is false. once I make it true,sounds should not play.This boolean is working well.

Problem is that once I checked the button(sound OFF) sound is getting OFF permanantly.Again Button click is not working as expected.

How do I change the code to work it well?


Solution

  • Have you checked how often the changed() method is called? Use Gdx.app.log() for logging. Or try using a different Listener, like ClickedListener for the button.

    You could also make you own Button, class MyButton extends Button to keep a cleaner code. Here is how I solved it.