gpt4 book ai didi

java - 切换按钮不适用于 SharedPreferences

转载 作者:行者123 更新时间:2023-12-01 22:48:46 26 4
gpt4 key购买 nike

我在应用程序中使用开关按钮来打开/关闭音乐。我正在使用 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();

}
}
});
}

}

`

最佳答案

您将 boolean 状态保存到键 NameOfThingToSave 下的共享首选项,并在 onCreate 上使用键 value 检索它。

在onCreate中适当设置键值:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
musicSwitch = findViewById(R.id.sLLmusicSwitch);

SharedPreferences sharedpreferences = getSharedPreferences("save",
Context.MODE_PRIVATE);
switchCheckListener();

musicSwitch.setChecked(sharedpreferences.getBoolean("NameOfThingToSave", false));
}

关于java - 切换按钮不适用于 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com