c# - 为什么我的列表视图没有在 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();
,但它不起作用。有什么我一直想念的吗?
解决方案
此代码仅将项目添加到列表中,但不更新数组适配器:
tasks.Add(listItem);
将项目直接添加到适配器:
adapter.Add(listItem);
或者在将项目添加到列表后,清除适配器并将列表重新添加到其中:
adapter.Clear();
adapter.Add(tasks);
推荐阅读
- git - 从本地和远程分支中删除以前的提交
- java - 是否可以调试 apache nifi 自定义处理器?
- c# - 为什么继续在 GetResult() 之前开始?
- python - 正确测试记录错误消息并在不满足条件时引发 SystemExit 的函数
- javascript - 每个元素的 url 拆分和连接 _ JavaScript
- c# - 抑制 ASP.NET Core 的自动 400 响应中的验证错误
- laravel - 是否有关于如何设置 ldap 服务器以及之后将其与简单的 laravel 应用程序连接的教程?
- html - CSS:删除滚动条并替换为表格中文本区域的可变高度
- javascript - 在用户触发事件后解决 puppeteer 中的 page.evaluate()
- database - 如何在一个由多个应用程序组成的平台上实现持续交付,这些应用程序都依赖一个数据库并相互依赖?