我在应用程序中使用开关按钮来打开/关闭音乐。我正在使用 SharedPreferences 来保存切换按钮的最后状态。但是,当我退出应用程序并再次运行时,它始终默认为“关闭”状态。我想始终保存用户选择的状态,即使他们关闭并再次运行应用程序也是如此。这是我的代码`public class SettingsView extends AppCompatActivity {
private Switch musicSwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
musicSwitch = findViewById(R.id.sLLmusicSwitch);
SharedPreferences sharedPrefs = getSharedPreferences("save", MODE_PRIVATE);
musicSwitch.setChecked(sharedPrefs.getBoolean("value", true));
switchCheckListener();
}
private void switchCheckListener() {
musicSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (musicSwitch.isChecked()) {
// saving state of the switch button
SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.apply();
musicSwitch.setChecked(true);
// turn on music
Repository.getInstance().startMusic();
Toast.makeText(getApplicationContext(), "Music on", Toast.LENGTH_SHORT).show();
} else {
// saving state of the switch button
SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.apply();
musicSwitch.setChecked(false);
//turn off music
Repository.getInstance().pauseMusic();
Toast.makeText(getApplicationContext(), "Music off", Toast.LENGTH_SHORT).show();
}
}
});
}
呼如林
相关分类