我正在尝试从使用 Mono for Android 和 .Net/C# (第 202 到 204 页)的专业 Android 编程一书中获取一个示例。
要注册和注销更改侦听器,它显示以下代码示例:
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
}
}
}
两者当然不能从转换RegisterOnSharedPreferenceChangeListener
为。UnregisterOnSharedPreferenceChangeListener
UserPreferences
ISharedPreferencesOnSharedPreferenceChangeListener
我不确定作者是如何做到这一点的。任何帮助将不胜感激。
我还尝试从wrox.com下载示例代码,但它不包括在示例代码中侦听首选项更改。
编辑:
以下代码可以编译,但OnSharedPreferenceChanged
不会在首选项中进行更新时被调用。
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
}
}