I am trying to get an example from the book Professional Android Programming with Mono for Android and .Net/C#
(pages 202 to 204) working.
To register and unregister a change listener it shows the following code sample:
using System;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Preferences;
namespace MonoForAndroidPreferences
{
[Activity(Label = "User Preferences")]
public class UserPreferences : PreferenceActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create your application here
this.AddPreferencesFromResource(Resource.Layout.userpreferences);
}
protected override void OnResume()
{
base.OnResume();
this.GetPreferences(FileCreationMode.Private).RegisterOnSharedPreferenceChangeListener(this);
}
protected override void OnPause()
{
base.OnPause();
this.GetPreferences(FileCreationMode.Private).UnregisterOnSharedPreferenceChangeListener(this);
}
public void OnSharedPreferenceChanged(ISharedPreferences prefs, string key)
{
// Do something with the changed value pointed to by key
}
}
}
Both RegisterOnSharedPreferenceChangeListener and UnregisterOnSharedPreferenceChangeListener of course cannot convert from UserPreferences to ISharedPreferencesOnSharedPreferenceChangeListener.
I’m not sure how the author meant for this to work. Any help would be greatly appreciated.
I also tried downloading the sample code from wrox.com but it did not include the listening for preferences changes in the sample code.
EDIT:
The following code compiles, but OnSharedPreferenceChanged never gets called when an update is made in the preferences.
public class UserPreferences : PreferenceActivity, ISharedPreferencesOnSharedPreferenceChangeListener
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create your application here
this.AddPreferencesFromResource(Resource.Layout.userpreferences);
}
protected override void OnResume()
{
base.OnResume();
this.GetPreferences(FileCreationMode.Private).RegisterOnSharedPreferenceChangeListener(this);
}
protected override void OnPause()
{
base.OnPause();
this.GetPreferences(FileCreationMode.Private).UnregisterOnSharedPreferenceChangeListener(this);
}
void ISharedPreferencesOnSharedPreferenceChangeListener.OnSharedPreferenceChanged(ISharedPreferences prefs, string key)
{
// Do something with the changed value pointed to by key
}
}
You need to use
instead of