SharedPreferences - OnSharedPreferenceChangeListener

纵然是瞬间 提交于 2019-12-12 18:26:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!