Sunday, July 15, 2012
(adsbygoogle = window.adsbygoogle || []).push({});

Android preference change listener implementation

In Android applications, there are scenarios we need to listen for changes to preferences. For example, a main activity would like to refresh itself based on a change in preference. Android provides the OnSharedPreferenceChangeListener which would help in achieving this.

The following example demonstrates the preference change listener.

Android preference change listener example

Implement a preference change listener in the main activity.
private class PreferenceChangeListener 
implements OnSharedPreferenceChangeListener {

 public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
  if ( key.equals("test_preference_key") ) {
   Log.v("PreferenceChange", "**** KEY test_preference_key modified ****");

Preferences XML looks as below for the above listener. We have a "test_preference_key" whose changes this activity is interested in listening.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="">
    <PreferenceCategory android:key="test_category_key" android:title="@string/test_category_string">
  <EditTextPreference android:title="@string/test_preference_string"

Create an object of preference change listener and register for change notifications in onCreate method of the activity.
public void onCreate(Bundle savedInstanceState) {

 mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
 mPreferenceListener = new PreferenceChangeListener();

Un-register the preference change listener in the activity onDestroy method.
public void onDestroy() {

The complete example can be downloaded from here.
(adsbygoogle = window.adsbygoogle || []).push({});

Contact Form


Email *

Message *

Back to Top