6

I've got this activity and have a problem with OnSharedPreferenceChanged not being called. My use case is that i want to show preference value in preference description. Code below translated is translated from java where works perfectly fine.

[Activity]          
public class PrefActivity : PreferenceActivity, ISharedPreferencesOnSharedPreferenceChangeListener
{

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        AddPreferencesFromResource(Resource.Xml.preferences);
    }

    protected override void OnResume()
    {
        base.OnResume();
        PreferenceScreen.SharedPreferences.
            RegisterOnSharedPreferenceChangeListener(this);
    }

    protected override void OnPause()
    {
        base.OnPause();
        PreferenceScreen.SharedPreferences.
            UnregisterOnSharedPreferenceChangeListener(this);
    }
    #region ISharedPreferencesOnSharedPreferenceChangeListener implementation
    public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key)
    {
        Preference pref = FindPreference(key);

        if (pref is ListPreference)
        {
            ListPreference listPref = (ListPreference)pref;
            listPref.Summary = listPref.Entry;
        }
    }
    #endregion
} 

Iam using Xamarin.Android v4.6.8 code above is my last attempt to make this working ive also tried using PreferenceScreen.PreferenceChange event for handling preference changes but with no results.

Tahnks for help.

FluffyCroc
  • 162
  • 1
  • 9

1 Answers1

8

Ive found solution! changing

PreferenceScreen.SharedPreferences.
RegisterOnSharedPreferenceChangeListener(this);

to

PreferenceManager.GetDefaultSharedPreferences(this).
RegisterOnSharedPreferenceChangeListener(this);

will do the trick.

I hope that it will help somebody.

FluffyCroc
  • 162
  • 1
  • 9
  • 1
    Sure did for me too. Very helpful. – Jannie Theunissen Nov 05 '13 at 15:32
  • 2
    Hey.I'm implementing the same thing but using a preference fragment instead. So i have the OnPause and OnResume methods inside my fragment class with the PreferenceManager.GetDefaultSharedPreferences(Activity). RegisterOnSharedPreferenceChangeListener(this) and unregister it in OnPause. However,they're are still not called inside my fragment. Should the implementation be different using a PreferenceFragment? – naffie Jul 23 '15 at 18:27