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

Persistent Switch toggle not working as expected

我正在尝试保留一个切换按钮,但是当我离开 activity 它没有保留 value.I 我在 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);