在 Xamarin 应用程序中将项目添加到 Android 上的 ListView

Add items to ListView on Android in Xamarin application

我正在尝试在 Xamarin 应用程序中重新混合 the base Android advice for adding items to a ListView,但到目前为止我都失败了。

在 Xamarin Studio 中,我创建了一个 Android 应用程序,目标是 Latest 和 Greatest,以及所有默认设置。然后我将 ListView 添加到我的 activity 并给它一个 id @android:id/list。我已将 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.AddNotifyDataSetChanged 方法都被调用而没有错误,Toast 出现在我的设备屏幕上。

但是,项目 "Another Item!" 没有出现在我的列表中。

我确实注意到链接问题和我的解决方案之间存在 很大 差异。链接问题的代码如下:

setListAdapter(adapter);

我反而做了:

ListAdapter = adapter;

因为 setListAdapter 方法在我的 Xamarin 解决方案中不可用,我曾假设 属性 setter 是为了做同样的事情。

长话短说:我需要做什么才能将项目动态添加到我的 ListView?

您正在列表中添加项目,但适配器不知道该列表。你应该做的是将项目添加到适配器:

adapter.Add ("Another Item!");