我试图在Xamarin应用程序中重新混合the base Android advice for adding items to a ListView,但到目前为止我还没有失败。
在Xamarin Studio中,我创建了一个 Android应用,目标是最新和最好的,以及所有默认设置。然后,我在我的活动中添加了ListView
,并为其指定了@android:id/list
。我已将活动代码更改为:
[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;
因为我的Xamarin解决方案中没有setListAdapter
方法,并且我认为属性设置器也是如此。
长话短说:我需要做些什么来动态地将项目添加到我的ListView?
答案 0 :(得分:4)
您正在列表中添加项目,但适配器不知道该列表。你应该做的是将项目添加到适配器:
adapter.Add ("Another Item!");