Search code examples
c#androidxamarinxamarin.androidandroid-arrayadapter

Updating the value of an item in ArrayAdapter of Xamarin Android


I have a list of the form:

var list = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1);
list.Add("George");
list.Add("Abraham");

in a Xamarin Android app.

How can I modify the first item of the list from "George" to "Donald" (without creating a new list with correct item)?

Something like:

list[0] = "Donald"

Solution

  • You need to invoke the method NotifyDataSetChanged after updating the ItemSource of ListView .

    The definition of NotifyDataSetChangedin the Android's documentation is as follows

    Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

    list[0] = "Donald"      
    list.NotifyDataSetChanged();
    

    Update

    You could create the Adapter with a string list like following

    List<string> ItemsSource = new List<string>() {"George","Abraham" };
    ItemsSource.Add("Lucas");
    var list = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1,ItemsSource);
    
    var adapter = listView.Adapter as ArrayAdapter;
    adapter.Remove(s[0]);
    adapter.Insert("Donald",0);
    adapter.NotifyDataSetChanged();
    

    Option 2

    You could create a custom adapter (subclass of BaseAdapter) so that you can set the value directly .