简体   繁体   中英

why isn't my listview refreshed in xamarin.android

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM