首页 > 解决方案 > 为什么我的列表视图没有在 xamarin.android 中刷新

问题描述

你好我有以下代码

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

 }  

我的问题是为什么当我点击我的按钮时我的列表视图没有更新。我不明白它,因为我用过adapter.NotifyDataSetChanged();,但它不起作用。有什么我一直想念的吗?

标签: c#xamarin.androidrefreshadapter

解决方案


此代码仅将项目添加到列表中,但不更新数组适配器:

tasks.Add(listItem);

将项目直接添加到适配器:

adapter.Add(listItem);

或者在将项目添加到列表后,清除适配器并将列表重新添加到其中:

adapter.Clear();
adapter.Add(tasks);

推荐阅读