【发布时间】:2017-03-11 14:33:25
【问题描述】:
我正在使用 C# 在 Xamarin、Visual Studio 2015 上开发 Android 应用程序。我有一个框,用户必须在其中输入字符串值,然后当单击按钮时,我希望将此值添加到微调器并保存并重新加载以供下次打开,这样他就可以选择他输入的值而无需重新输入。到现在为止我没有问题,我的想法奏效了。但我正在苦苦挣扎的是:如果用户输入了一个值然后单击按钮,然后输入另一个值,则只有最后一个值被保存并显示在重新打开APP时的微调器。我想要的是:用户输入的每个值都需要保存并显示在微调器中。然后如果用户想删除他之前输入的值,一个删除项目的按钮。
这是我到目前为止所做的:
string user;
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
var items = new List<string>() { "1", "2", "3" };
Button button4 = FindViewById<Button>(Resource.Id.button4);
Spinner spinner = FindViewById<Spinner>(Resource.Id.spinner1);
EditText input = FindViewById<EditText>(Resource.Id.input);
user = input.Text;
button4.Click += delegate
{
user = input.Text;
items.Add(user);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("try", user);
editor.Apply();
};
user = prefs.GetString("try", "no");
items.Add(user);
var adapter3 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);
spinner.Adapter = adapter3;
当我重新打开应用程序时,这些代码将用户输入添加并保存到微调器,但如果用户输入了两个值,则只保存最后一个值。我想要的是每个值都保存并显示在微调器中。 提前谢谢你..
【问题讨论】:
-
您只是将最近的值保存到首选项。如果要存储多个值,则需要将它们存储在数组或列表中并将它们序列化为首选项。
-
使用 putStringSet 将字符串集合存储在 SharedPrefence 中,然后使用 getStringSet 填充微调器。