简体   繁体   中英

SharedPreferences - OnSharedPreferenceChangeListener

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() .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM