Add items to ListView on Android in Xamarin application
Asked Answered
3

1

6

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?

3d answered 14/9, 2015 at 14:21 Comment(0)
R
4

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!");
Referendum answered 14/9, 2015 at 14:32 Comment(2)
Excellent. That works just fine, solves my immediate problem. You wouldn't happen to have any insights as to why Xamarin allows you to directly add items to the adapter, as opposed to linked Java solution that requires a backing ArrayList?3d
@Jeroen: You can add and item to ArrayAdapter directly in Java too.Referendum

© 2022 - 2024 — McMap. All rights reserved.