Search code examples
javaandroidlibgdxscene2d

ImageButton and Preferences


How can I create an ImageButton (musicButton) that control setting music on or off ?

I have GamePrefs class that has these 2 methods

public static void setBoolean(String name, boolean val) {
    prefs.setBoolean(name, val);
    prefs.flush();
}

public static boolean getBoolean(String name) {
    return prefs.getBoolean(name);
}

I have two images for the musicButton

Texture t1 = new Texture("music");
Texture t2 = new Texture("music_off");
TextureRegion tr1 = new TextureRegion(t1);
TextureRegion tr2 = new TextureRegion(t2);

I know I need to make an ImageButtonStyle but I have many fields imageUp, imageDown, checked, checkedOver... I don't know which two I should use

and I need it to respond to touch and changing current music setting to on or off

something like this :

GamePrefs.setBoolean("music", false) or GamePrefs.setBoolean("music", true)

and I will use getBoolean() to play music or not

Any help ?


Solution

  • For creating such kind of buttons I used ImageButton.ImageButtonStyle with up and checked attributes:

    public Button getMusicButton() {
        final Button button = new ImageButton(getMusicButtonStyle());
        button.setChecked(Prefs.isMusicOn());
        button.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                MusicHandler.getInstance().toggleMusic();
            }
        });
        return button;
    }
    
    private ImageButton.ImageButtonStyle getMusicButtonStyle() {
        ImageButton.ImageButtonStyle style = new ImageButton.ImageButtonStyle();
        style.up = musicOffDrawable;
        style.checked = musicOnDrawable;
        return style;
    }
    

    For music and sounds I have MusicHandler class with this method:

    public void toggleMusic() {
        Prefs.toggleMusic();
        if (!Prefs.isMusicOn()) {
            music.stop();
        } else {
            music.play();
        }
    }
    

    And finally in Prefs class there are:

    public static boolean isMusicOn() {
        return pref.getBoolean(MUSIC_ON);
    }
    
    public static void toggleMusic() {
        pref.putBoolean("music_on", !isMusicOn());
        pref.flush();
    }