Best Place to Place onSharedPreferenceChangeListener

I am trying to add a parameter to my application. I added a new setting, but I'm not sure where to put it OnSharedPreferenceChangeListener. I put it into action and added Log.d(), but it Log.d()never starts. Any ideas?

+3
source share
2 answers

The best place according to the Android dock is:

@Override
protected void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences()
            .unregisterOnSharedPreferenceChangeListener(this);
}

And you must store the listener in a field variable (or use the Activity object itself - as in the above source code) so that it does not collect garbage.

those. An anonymous class object cannot be used as OnSharedPreferenceChangeListener.

+3
source

, setOnPreferenceChangeListener. , Activity, PreferenceActivity. , . - :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    Preference myPreference = findPreference("my_pref");
    myPreference.setOnPreferenceChangeListener(this);
}
0

All Articles