我想保存游戏中的设置(bgMusic,声音和振动),但在启动时加载应用程序会崩溃。 代码是:
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private boolean bgMusicToggleState, soundToggleState, vibratorToggleState;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
dialog.setContentView(R.layout.pause_dialog);
dialog.hide();
initDialog();
this.preferences = this.getSharedPreferences(GAME_NAME, MODE_PRIVATE);
this.editor = preferences.edit();
...
}
...
public void saveMusicSettings(){
editor.putBoolean("bgMusicToggleState", bgmusic_toggle.isChecked());
editor.commit();
}
public void saveVibratorSettings(){
editor.putBoolean("vibratorToggleState", vibrateToggle.isChecked());
editor.commit();
}
public void saveSoundSettings(){
editor.putBoolean("soundToggleState", sounds_toggle.isChecked());
editor.commit();
}
...
private void initDialog(){
/// The App crashes here
bgMusicToggleState = preferences.getBoolean("bgMusicToggleState", false);
continue_Button = (Button) dialog.findViewById(R.id.continue_button);
restart_Button = (Button) dialog.findViewById(R.id.restart_button);
exit_Button = (Button) dialog.findViewById(R.id.exit_button);
continue_Button.setOnClickListener(pauseClick);
exit_Button.setOnClickListener(pauseClick);
restart_Button.setOnClickListener(pauseClick);
bgmusic_toggle = (ToggleButton) dialog.findViewById(R.id.backgroundsound_toggle);
bgmusic_toggle.setChecked(bgMusicToggleState);
bgmusic_toggle.setOnClickListener(toggleClickListener);
sounds_toggle = (ToggleButton) dialog.findViewById(R.id.soundtoggle);
sounds_toggle.setChecked(soundToggleState);
sounds_toggle.setOnClickListener(toggleClickListener);
vibrateToggle = (ToggleButton)dialog.findViewById(R.id.vibrate_toggle);
vibrateToggle.setChecked(vibratorToggleState);
vibrateToggle.setOnClickListener(toggleClickListener);
}
- >在toggleClickListener中调用保存设置 如果preferenes和编辑器在initMethod中,它确实有所不同...... 可能是ToggleButtons在Dialog中,还是我必须在一个方法中执行此操作? 我希望你能帮助我。 谢谢!
答案 0 :(得分:2)
初始化initDialog
对象后,您必须先调用SharedPreference
,而不是之前。
变化
initDialog();
this.preferences = this.getSharedPreferences(GAME_NAME, MODE_PRIVATE);
this.editor = preferences.edit();
到
this.preferences = this.getSharedPreferences(GAME_NAME, MODE_PRIVATE);
this.editor = preferences.edit();
initDialog();