持久开关切换未按预期工作



我试图持久化一个开关按钮,但当我离开活动时,它不会持久化值。我正在设置setUpBooleanDefectsSwitch函数的共享首选项我缺少什么?

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setUpBooleanDefectsSwitch()
SharedPreferences prefs = getSharedPreferences("booleanDefects",Context.MODE_PRIVATE);
SharedPreferences.OnSharedPreferenceChangeListener listener;


listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("boolDefects")){
boolean boolDefectsSwitch = sharedPreferences.getBoolean("boolDefects",false);
System.out.println("Boolean Defects Changed");
System.out.println(boolDefectsSwitch);
booleanDefectsSwitch.setChecked(boolDefectsSwitch);
}
}
};




}
private void setUpBooleanDefectsSwitch(){
booleanDefectsSwitch = (Switch) findViewById(R.id.booleanDefects);
final SharedPreferences booleanDefectsPrefs = getSharedPreferences("booleanDefects",Context.MODE_PRIVATE);
booleanDefectsSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = booleanDefectsPrefs.edit();
editor.putBoolean("boolDefects",isChecked);
editor.commit();
}
});
}

您正在寻找SharedPreferences的全局引用。

尝试替换

SharedPreferences prefs = getSharedPreferences("booleanDefects", Context.MODE_PRIVATE);
SharedPreferences.OnSharedPreferenceChangeListener listener;
listener = new  

带有

SharedPreferences prefs = getSharedPreferences("booleanDefects", Context.MODE_PRIVATE);
prefs.registerOnSharedPreferenceChangeListener(new 

或者只是在监听器之后的末尾添加这个

prefs.registerOnSharedPreferenceChangeListener(listener);

相关内容

  • 没有找到相关文章

最新更新