SwitchPreference switchPreference = new SwitchPreference(preferenceScreen.getContext());
switchPreference.setKey(sensor.getName());
switchPreference.setTitle(sensor.getName());
switchPreference.setChecked(true);


如果我使用以下命令检查开关的状态

switchPreference.isChecked()


它将正确的布尔值返回为true。但是,开关的图形始终处于上一次运行时设置的状态。

这些开关是在onCreate()中动态创建的

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences); //almost empty
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    prefs.registerOnSharedPreferenceChangeListener(this);
    PreferenceScreen preferenceScreen = this.getPreferenceScreen();
    PreferenceCategory preferenceCategory = new PreferenceCategory(preferenceScreen.getContext());
    preferenceCategory.setTitle("Sensor List");
    preferenceScreen.addPreference(preferenceCategory);

    for (TrackingData sensor : SensorService.data)
    {
        SwitchPreference switchPreference = new SwitchPreference(preferenceScreen.getContext());
        switchPreference.setKey(sensor.getName());
        switchPreference.setTitle(sensor.getName());
        switchPreference.setChecked(true);
        Log.d(TAG_SENSOR,switchPreference.getKey() + "'s status is " + switchPreference.isChecked());
        preferenceCategory.addPreference(switchPreference);
    }
}


public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{


    SwitchPreference preference = (SwitchPreference) findPreference(key);
    boolean value = preference.isChecked();
    if (value)
    {
        //start tracking this sensor
        Log.d(TAG_SENSOR, key + " tracking enabled");
    }
    else
    {
        //stop tracking this sensor
        Log.d(TAG_SENSOR, key + "tracking disabled");
    }

}

最佳答案

经过一番修补,我发现解决方法是将SwitchPreference的持久值设置为false

10-08 18:37