我正在尝试重新混合 the base Android advice for adding items to a ListView在 Xamarin 应用程序中,但到目前为止我失败了。
在 Xamarin Studio 中,我创建了一个Android 应用,目标是最新和最伟大的,以及所有默认设置。然后,我将 ListView
添加到我的 Activity 中,并为其指定了 @android:id/list
的 ID。我已将 Activity 的代码更改为:
[Activity (Label = "MyApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : ListActivity
{
List<string> items;
ArrayAdapter<string> adapter;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
items = new List<string>(new[] { "Some item" });
adapter = new ArrayAdapter<string> (this, Android.Resource.Layout.SimpleListItem1, items);
ListAdapter = adapter;
FindViewById<Button> (Resource.Id.myButton).Click += HandleClick;
}
protected void HandleClick(object sender, EventArgs e)
{
items.Add ("Another Item!");
adapter.NotifyDataSetChanged ();
Android.Widget.Toast.MakeText (this, "Method was called", ToastLength.Short).Show();
}
}
我构建应用程序并在我的 Nexus 5 设备上运行它。应用程序启动正常,我可以单击按钮,然后看到调试器命中处理程序。调试器没有显示其他问题,items.Add
和 NotifyDataSetChanged
方法都被正确调用,Toast
出现在我的设备屏幕上.
但是,项目“Another Item!”
没有出现在我的列表中。
我确实注意到链接的问题和我的解决方案之间有一个很大的区别。链接问题的代码如下:
setListAdapter(adapter);
我反而做了:
ListAdapter = adapter;
因为 setListAdapter
方法在我的 Xamarin 解决方案中不可用,我曾假设属性 setter 也有同样的作用。
长话短说:我需要做什么才能将项目动态添加到我的 ListView?
最佳答案
您正在列表中添加项目,但适配器不知道该列表。您应该做的是将项目添加到适配器:
adapter.Add ("Another Item!");
关于c# - 在 Xamarin 应用程序中将项目添加到 Android 上的 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32567237/