我在应用程序中使用开关按钮来打开/关闭音乐。我正在使用 SharedPreferences 来保存切换按钮的最后状态。但是,当我退出应用程序并再次运行时,它始终默认为“关闭”状态。我想始终保存用户选择的状态,即使他们关闭并再次运行应用程序也是如此。这是我的代码`public class SettingsView extends AppCompatActivity {private Switch musicSwitch;@Overrideprotected 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(); } } });}
1 回答
呼如林
TA贡献1798条经验 获得超3个赞
您将布尔状态保存到 key 下的共享首选项中NameOfThingToSave,并在 onCreate 上使用 key 检索它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));
}
添加回答
举报
0/150
提交
取消