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

5 comments :

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. It has three simple steps to make Android application. First of all you have to choose an app then customize your content (text) of your choice and even pictures.
    Freedom Apk

    ReplyDelete
  3. But the openness and its massive market share made Android vulnerable to frequent security attacks. There are many instances when security of millions of Android devices has been impacted by security flaws or bugs like Stagefright, 'Certifi-gate' mRST, FakeID, Installer Hijacking and TowelRoot.very coold video app

    ReplyDelete
  4. lucky patcher apk

    https://luckypatcherappdownload.com/apk-latest/

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top