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

Jer*_*oen 6 c# android listactivity android-listview xamarin

我正在尝试重新混合基本的Android建议,将项目添加到 Xamarin应用程序中的ListView,但到目前为止,我失败了.

在Xamarin Studio中,我创建了一个针对最新和最大Android应用程序,以及所有默认设置.然后我添加了一个到我的活动并给它一个id .我已将活动的代码更改为: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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我构建应用程序并在我的Nexus 5设备上运行它.应用程序启动正常,我可以单击按钮,然后看到调试器点击处理程序.调试器没有显示任何其他问题,items.Add并且这些NotifyDataSetChanged方法被调用而没有错误,并且Toast显示在我的设备屏幕上.

但是,该项目"Another Item!"不会出现在我的列表中.

我注意到链接问题和我的解决方案之间存在一个很大的区别.链接问题的代码如下:

setListAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)

我做了:

ListAdapter = adapter;
Run Code Online (Sandbox Code Playgroud)

因为这个setListAdapter方法在我的Xamarin解决方案中不可用,并且我假设属性设置器也是这样做的.

简而言之:我需要做些什么才能动态地将项目添加到ListView中?

Gio*_*rgi 4

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

adapter.Add ("Another Item!");
Run Code Online (Sandbox Code Playgroud)