问题
I googled this and found a few answers which I find confusing since I am a beginner. I am trying to implement the OnSharedPreferenceChangeListener()
to my SharedPreferences
to make something happen with the change.
My code so far is:
final SharedPreferences rates_storage = this.getApplicationContext().getSharedPreferences("uk.chiraggalaiya.test", 0);
final SharedPreferences.Editor rates_storage_editor = rates_storage.edit();
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rates_storage_editor.putString("something", "something");
rates_storage_editor.apply();
}
});
However now I am not sure how to implement the OnChangeListener()
.
回答1:
You can use following code snippet to register your ChangListener for the SharedPreference:
SharedPreferences.OnSharedPreferenceChangeListener prefListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
....
}
};
rates_storage.registerOnSharedPreferenceChangeListener(prefListener);
来源:https://stackoverflow.com/questions/36272406/sharedpreferences-onsharedpreferencechangelistener