【发布时间】:2015-12-10 14:21:57
【问题描述】:
我正在尝试在 Xamarin 应用程序中重新混合 the base Android advice for adding items to a ListView,但到目前为止我失败了。
在 Xamarin Studio 中,我创建了一个 Android 应用,目标是最新和最好的,以及所有默认设置。然后我在我的活动中添加了一个ListView,并给它一个ID @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;
因为 setListAdapter 方法在我的 Xamarin 解决方案中不可用,并且我认为属性设置器也打算这样做。
长话短说:我需要做什么才能将项目动态添加到我的 ListView?
【问题讨论】:
标签: c# android android-listview xamarin listactivity