Hello I have the following code
public class MainActivity : Activity
{
Button b;
Button c;
TextView t;
List<string> tasks = new List<string>();
ListView lView;
ArrayAdapter<string> adapter;
int count = 0;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
b = FindViewById<Button>(Resource.Id.btn);
c = FindViewById<Button>(Resource.Id.clearBtn);
t = FindViewById<TextView>(Resource.Id.tView);
lView = FindViewById<ListView>(Resource.Id.listView);
adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1,tasks);
lView.Adapter = adapter;
b.Click += ChangeTextAndAdd;
}
}
private void ChangeTextAndAdd(object sender, EventArgs e)
{
t.Text = "text is changed";
string listItem = string.Format("task{0}", count++);
tasks.Add(listItem);
adapter.NotifyDataSetChanged();
}
My question is why doesn't my listview update when I click on my button. I don't understand it because I have used adapter.NotifyDataSetChanged();
but it doesn't work. Is there something I've been missing?
This code only add the item to the list, but doesn't update the array adapter:
tasks.Add(listItem);
Either add the item directly to the adapter:
adapter.Add(listItem);
or after you add the item to the list, clear the adapter and re-add the list to it:
adapter.Clear();
adapter.Add(tasks);