Reputation: 449
I have a ListPreference containing colors. Only when I restart the application that the colors are being changed, not directly. How do I make it change directly when I click ?
public class Preferences extends PreferenceActivity {
SharedPreferences sharedpreferences;
SharedPreferences sharedpreferences2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
sharedpreferences2 = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
ListPreference listPreference = (ListPreference) findPreference("Color");
CharSequence entry = listPreference.getEntry();
final String value = listPreference.getValue();
final ListView rel = this.getListView();
if (sharedpreferences2.contains("Color")) {
if (value.toString().equals("Red")) {
rel.setBackgroundColor(Color.RED);
}
if (value.toString().equals("Blue")) {
rel.setBackgroundColor(Color.BLUE);
}
if (value.toString().equalsIgnoreCase("Green")) {
rel.setBackgroundColor(Color.GREEN);
}
}
}
Upvotes: 0
Views: 96
Reputation: 11608
you will need the OnSharedPreferenceChangeListener. Use registerOnSharedPreferenceChangeListener()
in your onResume()
and override the onSharedPreferenceChanged()
method to perform actions on preference change.
Unregister the listener in your onPause()
method.
P.S. PreferenceActivity
is deprecated, consider using PreferenceFragment instead.
Upvotes: 1