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");
}
}
答案 0 :(得分:0)
经过一些修补,我发现修复是将SwitchPreference的持久值设置为false