【问题标题】:why isn't my listview refreshed in xamarin.android为什么我的列表视图没有在 xamarin.android 中刷新
【发布时间】:2023-04-01 09:34:01
【问题描述】:

你好我有以下代码

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();,但它不起作用。有什么我遗漏的吗?

【问题讨论】:

  • 试试这个listView.setAdapter(adapter); adapter.notifyDataSetChanged();
  • 也不起作用。这可能是由于 Visual Studio 中的错误造成的吗?因为我之前已经厌倦了NotifyDataSetChaged(),而且效果很好。

标签: c# xamarin.android refresh adapter


【解决方案1】:

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

tasks.Add(listItem);

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

adapter.Add(listItem);

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

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

【讨论】:

  • 它有效,但我不明白。 adapter = new ArrayAdapter&lt;string&gt;(this, Android.Resource.Layout.SimpleListItem1,tasks); 不镜像适配器中列表中的每个项目吗?当我刷新它时,它不应该只是遍历列表中的所有项目吗?如果我将它们直接添加到适配器,则列表将变得毫无用处。
  • @GeorgiYakov 当您初始化适配器时,它只是将您传递给它的列表中的项目放到它自己的项目中。它不再知道对您的项目列表所做的更改。
  • 但是当我使用adapter.NotifyDataSetChaged() 时会发生什么。当我已经将新项目添加到列表中时,它不会刷新适配器吗?
  • 当您添加新项目时,您只是将其添加到列表中。阵列适配器自己的列表已与您的原始列表断开连接。所以如果你不直接将item添加到适配器并调用NotifyDataSetChanged(),适配器的列表值仍然是原来的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多