在Android的Xamarin应用程序中添加项目到ListView
本文关键字:添加 项目 ListView 应用程序 Android Xamarin | 更新日期: 2023-09-27 18:12:44
我正在尝试在Xamarin应用程序中将项目添加到ListView的基本Android建议进行重新组合,但到目前为止我失败了。
在Xamarin Studio中,我创建了一个Android应用,目标是最新和最伟大的,以及所有默认设置。然后,我将一个ListView
添加到我的活动中,并给它一个@android:id/list
的id。我已经改变了活动的代码如下:
[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解决方案中不可用,并且我假设属性设置器也意味着做同样的事情。
长话短说:我需要做什么来动态地添加项目到我的ListView?
您正在列表中添加项目,但适配器不知道该列表。您应该做的是将项添加到适配器:
adapter.Add ("Another Item!");