我将尝试在Xamarin应用程序中重新制作添加项到ListView的基本Android建议,但目前我失败了。
在Xamarin Studio中,我创建了一个针对“最新和最伟大”的Android应用程序,并使用所有默认设置。然后我向我的活动中添加了一个
我建立了一个应用并在我的Nexus 5设备上运行它。应用程序正常启动,我可以点击按钮,并看到调试器命中处理程序。调试器没有显示其他问题,
然而,项目
我注意到链接的问题和我的解决方案之间有一个很大的区别。在链接的问题中,代码如下:
因为在我的 Xamarin 解决方案中没有
简而言之:我需要做什么才能动态地向我的 ListView 添加项目?
在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;
因为在我的 Xamarin 解决方案中没有
setListAdapter
方法,我曾经认为属性设置器是用来做同样的事情的。简而言之:我需要做什么才能动态地向我的 ListView 添加项目?