【发布时间】:2015-12-07 19:38:21
【问题描述】:
首先我必须提到我是 Android 应用程序开发的新手。我正在使用 Xamarin (C#) 开发应用程序。这就是问题所在。我想编写简单的 ToDoList 应用程序来学习如何在活动之间存储/共享数据。
按钮“添加”放置在主布局中。当用户单击它时,将显示另一个屏幕,用户可以在其中命名(EditText)任务并添加其描述(EditText)。当用户单击该屏幕中的“完成”按钮时,应用程序会将用户重定向到主屏幕并将用户的任务添加到列表视图。
我做了一些研究,发现我可以使用 SharedPreferences、将数据保存到设备上的文件或 sql 来做到这一点。
我决定使用 SharedPreferences。问题是,我发现的关于 SharedPrefences 的所有内容(我搜索了很多,相信我)都是用 Java 编写的,这不会是一个大问题,但没有人提到使用共享偏好在不同活动之间共享数据。我的代码在下面,我真的为此苦苦挣扎了一天,所以请帮助我。
我的 MainActivity(“添加”按钮所在的位置):
public class MainActivity : Activity
{
Button add;
ListView list;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
///set layout
SetContentView(Resource.Layout.Main);
///define variables, buttons, lists
add = FindViewById<Button>(Resource.Id.add);
list = FindViewById<ListView>(Resource.Id.list);
///get string from secondActivity
var prefs = Application.Context.GetSharedPreferences("todolist", FileCreationMode.Private);
var preference = prefs.GetString("task", null);
///add string (preference) to list
List<string> lista = new List<string>();
lista.Add(preference);
///"convert" list to listview
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Resource.Layout.Main, lista);
list.Adapter = adapter;
add.Click += delegate
{
StartActivity(new Intent(this, typeof(addActivity)));
};
}
}
我的第二个屏幕(第二个活动):
public class addActivity : Activity
{
/// define variables and create list
Button complete;
EditText name, description;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.add);
///variables
complete = FindViewById<Button>(Resource.Id.complete);
name = FindViewById<EditText>(Resource.Id.name);
description = FindViewById<EditText>(Resource.Id.description);
///converting to string
string title = name.Text.ToString();
string content = description.Text.ToString();
///pass string to MainActivity
complete.Click += delegate
{
if (String.IsNullOrEmpty(title))
{
Toast.MakeText(this, "Please enter task name", ToastLength.Short).Show();
}
else
{
var prefs = Application.Context.GetSharedPreferences("todolist", FileCreationMode.Private);
var prefEditor = prefs.Edit();
prefEditor.PutString("task", title);
prefEditor.Commit();
Toast.MakeText(this, "Task added", ToastLength.Short).Show();
StartActivity(new Intent(this, typeof(MainActivity)));
}
};
}
}
【问题讨论】:
标签: c# android listview xamarin sharedpreferences