在偏好中存储音乐ON / OFF状态-LibGdx

时间:2017-06-08 05:15:14

标签: java libgdx

我有这样的音乐按钮:

private void drawMusicButton() {
    musicButton = new ImageButton(new TextureRegionDrawable(musicTexture1),new TextureRegionDrawable(musicTexture2), new TextureRegionDrawable(musicTexture2));
    musicButton.setChecked(!game.menuMusicBool);
    stage.addActor(musicButton);

    musicButton.setPosition(UiConstants.MUSIC_X, UiConstants.MUSIC_Y, Align.bottom);
    musicButton.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            if (!game.buttonClickSoundBool&&game.soundBool)
                buttonClickSound.play();
            if (game.menuMusicBool)
                game.menuMusicBool = false;
            else
                game.menuMusicBool = true;
            musicStateManager.saveMusicState();
        }
    });
}

最初menuMusicBool为真。

public boolean menuMusicBool = true;

我希望优先存储音乐ON / OFF状态,以便在重新启动游戏时,我可以获得之前选择的状态。

我的偏好类是这样的:

public class MusicStateManager {

  private final Preferences prefs;
  public final Mgame game;

  private static final String MUSIC_STATE = "musicState";

  public MusicStateManager(Mgame game){
      this.game = game;
      prefs = Gdx.app.getPreferences(Mgame.class.getName());
  }

  public void getPreferenceValues(){ }

  public void reset(){ }

  public void saveMusicState() {

    prefs.putBoolean(MUSIC_STATE, game.menuMusicBool);
    prefs.flush();
  }

  public void getMusicState() {
     game.menuMusicBool = prefs.getBoolean(MUSIC_STATE);
  } 

getMusicState()我在render()中调用。

但优先考虑的是,价值并没有得到妥善保存。 退出并重新启动游戏时,我无法保存以前的状态。

我在代码中做错了什么?

1 个答案:

答案 0 :(得分:1)

No data found

如果您想播放音乐,请使用public class MusicStateManager { private final Preferences prefs; public final Mgame game; private static final String PREF_NAME ="APP_NAME"; private static final String MUSIC_STATE = "musicState"; public MusicStateManager(Mgame game){ this.game = game; prefs = Gdx.app.getPreferences(PREF_NAME); game.menuMusicBool = prefs.getBoolean(MUSIC_STATE, true); // return true when key not found } public void saveMusicState(boolean musicState) { game.menuMusicBool = musicState; prefs.putBoolean(MUSIC_STATE, musicState); prefs.flush(); // music state changed and saved, now need to start or stop music if(game.menuMusicBool) // I supposed game having music object reference game.music.play(); else game.music.stop(); } public boolean getMusicState() { return prefs.getBoolean(MUSIC_STATE); } 作为标记

game.menuMusicBool

MusicButton的内部听众

public void playMusic(Music music){

    if(game.menuMusicBool && !music.isPlaying()){
         music.play();
         music.setLooping(true);
     }
}