您好,我有以下代码
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();
,但是它不起作用。有什么我想念的吗?
答案 0 :(得分:0)
此代码仅将项目添加到列表中,而不会更新阵列适配器:
tasks.Add(listItem);
直接将项目添加到适配器:
adapter.Add(listItem);
或在将项目添加到列表之后,清除适配器,然后将列表重新添加到其中:
adapter.Clear();
adapter.Add(tasks);