我正在开发 Xamarin Android应用程序。我不知道如何保存我在myfragment中的变量值。当我重新打开我的应用程序时,我想要恢复该值的值在完全关闭之后。我该如何实现呢?
答案 0 :(得分:0)
您可能想要使用SharedPreferences(Xamarin中的ISharedPreferences):
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutString ("your_string_key", "your_string_value");
editor.Apply();
您也可以远程保存其他类型的数据
答案 1 :(得分:0)
以下是我使用的示例,我在我的视图模型中的属性中保存了共享首选项(SettingsPreferences)中的值:
SpinnerItem _selectedNumberPlayers;
public SpinnerItem SelectedNumberPlayers
{
get { return _selectedNumberPlayers; }
set
{
if (_selectedNumberPlayers != value)
{
_selectedNumberPlayers = value;
SettingsPreferences.SelectedNumberPlayers = _selectedNumberPlayers.Index;
FireMyPlayersChanged(AppSection.Settings);
RaisePropertyChanged(() => SelectedNumberPlayers);
}
}
}
这是我的SettingsPreferences.SelectedNumberPlayers:
public static int SelectedNumberPlayers
{
get
{
return Settings.AppSettings.GetValueOrDefault(StringConstants.SelectedNumberPlayers, SelectedNumberPlayersDefault);
}
set
{
Settings.AppSettings.AddOrUpdateValue(StringConstants.SelectedNumberPlayers, value);
}
}
其中Settings.AppSettings是来自XAM设置nuget包的CrossSettings.Current。
要在应用启动时阅读您的变量,只需执行以下操作:
var myVar = SettingsPreferences.SelectedNumberPlayers;
答案 2 :(得分:0)
protected void saveset(){
var prefs =this.Activity.GetSharedPreferences("MyApp",FileCreationMode.Private);
var prefEditor = prefs.Edit();
prefEditor.PutString ("LoginUserName",LoginUserName.Text.Trim());
prefEditor.PutString ("ProfilePicture",ImageUrl);
prefEditor.PutString ("UserID", User_Id);
prefEditor.Commit();
}
protected void retrieveset(){
//retreive
var prefs =this.Activity.GetSharedPreferences("MyApp", FileCreationMode.Private);
LoginUserName.Text= prefs.GetString ("LoginUserName", string.Empty);
ImageUrl= prefs.GetString ("ProfilePicture", string.Empty);
User_Id = prefs.GetString ("UserID", string.Empty);
}