Sunday, July 15, 2012

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 {

 @Override
 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="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:key="test_category_key" android:title="@string/test_category_string">
  <EditTextPreference android:title="@string/test_preference_string"
      android:key="test_preference_key"
      android:summary="@string/test_preference_summary_string">
  </EditTextPreference>
  </PreferenceCategory>
</PreferenceScreen>

Create an object of preference change listener and register for change notifications in onCreate method of the activity.
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

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

Un-register the preference change listener in the activity onDestroy method.
@Override
public void onDestroy() {
 super.onDestroy();
 mPrefs.unregisterOnSharedPreferenceChangeListener(mPreferenceListener);
}

The complete example can be downloaded from here.
PreferenceChange

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top