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

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

本文介绍了在Xamarin应用程序中将项目添加到Android上的ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to remix the base Android advice for adding items to a ListView in a Xamarin application, but so far I'm failing.

在Xamarin Studio中,我创建了一个 Android应用,该应用针对最新和最伟大的以及所有默认设置.然后,我在活动中添加了ListView,并为其指定了@android:id/list的ID.我已将活动代码更改为此:

In Xamarin Studio, I've created an Android App targeting Latest and Greatest, and all default settings. I then added a ListView to my activity and gave it an id of @android:id/list. I've changed the activity's code to this:

[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出现在设备的屏幕上.

I build the app and run it on my Nexus 5 device. The application starts fine, I can click the button, and see the debugger hit the handler. The debugger shows no other problems, both items.Add and the NotifyDataSetChanged methods are called without error, and the Toast shows up on my device's screen.

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

However, the item "Another Item!" does not appear in my list.

我确实注意到,链接的问题和我的解决方案之间有一个 big 区别.链接的问题的代码如下:

I do note that there's one big difference between the linked question and my solution. Where the linked question has code like this:

setListAdapter(adapter);

我改为:

ListAdapter = adapter;

因为在我的Xamarin解决方案中没有setListAdapter方法,所以我假设属性设置程序的作用是相同的.

Because the setListAdapter method isn't available in my Xamarin solution, and I had assumed the property setter was meant to do the same.

长话短说:如何将项目动态添加到ListView中?

Long story short: what do I need to do to dynamically add items to my ListView?

推荐答案

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

You are adding item in your list but the adapter isn't aware of that list. What you should do is add the item to the adapter:

adapter.Add ("Another Item!");

这篇关于在Xamarin应用程序中将项目添加到Android上的ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 03:43