SharedPreferences
您是否在编写和阅读它们之间重新部署?这通常会擦掉SharedPreferences
.
我刚刚对它们进行了测试,它们在两个之间运行良好Activities
:
WritePrefsAcitivity.cs
using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
namespace Derrrp
{
[Activity (Label = "Derrrp", MainLauncher = true)]
public class WritePrefsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Write);
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
var prefsEditor = prefs.Edit();
var ed = FindViewById<EditText>(Resource.Id.editText1);
ed.AfterTextChanged += (sender, e) => {
prefsEditor.PutString("MyPref", e.Editable.ToString());
prefsEditor.Commit();
};
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
var intent = new Intent(this, typeof(ReadPrefsActivity));
StartActivity(intent);
};
}
}
}
ReadPrefsActivity.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
namespace Derrrp
{
[Activity (Label = "ReadPrefsActivity")]
public class ReadPrefsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.Read);
var tv = FindViewById<TextView>(Resource.Id.myTextView);
var button = FindViewById<Button>(Resource.Id.myButton);
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
button.Click += (sender, e) => {
tv.Text = prefs.GetString("MyPref", "");
};
}
}
}
defValue
可以设置为您想要的任何内容。如果您尝试获取的首选项为空,则将选择此值。
注意:如果您使用它来存储一些秘密信息,建议使用FileCreationMode.Private
甚至使用使其只能由应用程序读取的东西,例如加密。