Add items to ListView on Android in Xamarin application

Jeroen picture Jeroen · Sep 14, 2015 · Viewed 15.6k times · Source

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.

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();
    }
}

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.

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

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);

I instead did:

ListAdapter = adapter;

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

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

Answer

Giorgi picture Giorgi · Sep 14, 2015

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!");