public class Preferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.your_prefs);
ListPreference listPreference = (ListPreference) findPreference("preference_key");
if(listPreference.getValue()==null) {
// to ensure we don't get a null value
// set first value by default
listPreference.setValueIndex(0);
}
listPreference.setSummary(listPreference.getValue().toString());
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
return true;
}
});
}
}
listPreference.setSummary(servicePreference.getEntry().toString());
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Set the value as the new value
listPreference.setValue(newValue.toString());
// Get the entry which corresponds to the current value and set as summary
preference.setSummary(listPreference.getEntry());
return false;
}
});
The trick is to use getEntry() instead of getValue() and once the value is changed, to set the value explicitly and read back the entry.
// Retrieve & populate flash modes
List<String> flashmodes = params.getSupportedFlashModes();
if (flashmodes != null) {
final ListPreference lp = (ListPreference) findPreference("flash_list");
final String lp_basesummary = "Set the Flash mode. The default is 'auto'";
lp.setEntries(flashmodes.toArray(new CharSequence[flashmodes.size()]));
lp.setEntryValues(flashmodes.toArray(new CharSequence[flashmodes.size()]));
// If there's only one option, make it the default
if (flashmodes.size() == 1)
lp.setValueIndex(0);
lp.setSummary(lp_basesummary + " [" + lp.getEntry() + "]");
lp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Set the value as the new value
lp.setValue(newValue.toString());
// Get the entry which corresponds to the current value
// and set as summary
preference.setSummary(lp_basesummary + " [" + lp.getEntry() + "]");
return false;
}
});
} else {
// Remove the preference
((PreferenceGroup) findPreference("camera_preference")).removePreference(findPreference("flash_list"));
}
// Retrieve & populate focus modes
List<String> focusmodes = params.getSupportedFocusModes();
if (focusmodes != null) {
final ListPreference lp = (ListPreference) findPreference("focus_mode_list");
final String lp_basesummary = "Set the Focus mode. The default is 'auto'";
...