ListView无法访问列表的最后元素
我有一个要在屏幕上列出的对象列表,并使用带有适配器的ListView。我添加了一个listViewItem单击事件,例如:
lstViewData.ItemClick += OnListViewItemClicked;
事件本身:
private void OnListViewItemClicked(object sender, AdapterView.ItemClickEventArgs e)
{
for (int i = 0; i < lstViewData.Count; i++)
{
if (e.Position == i)
lstViewData.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Gray);
else
lstViewData.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Transparent);
}
lstViewData
中有5个元素。因此,出于for循环的目的,表示i
从0到4。它确实如此。
问题是i
到达列表的最后一个元素,我会发现一个错误 参考未设置为对象的实例。又名NullReferenceException,如果我没记错的话。
我去调试,发现列表的所有5个要素都不是无效的,一切都很好,索引永远不会超出范围。因此,我迷路了,我不知道为什么我的代码在尝试访问列表的最后一个元素时会断开。
I have a list of objects I want to list on the screen and im using a ListView with an adapter. And I have added a listViewItem click event like this:
lstViewData.ItemClick += OnListViewItemClicked;
The event itself:
private void OnListViewItemClicked(object sender, AdapterView.ItemClickEventArgs e)
{
for (int i = 0; i < lstViewData.Count; i++)
{
if (e.Position == i)
lstViewData.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Gray);
else
lstViewData.GetChildAt(i).SetBackgroundColor(Android.Graphics.Color.Transparent);
}
The lstViewData
has 5 elements in it. So for the purpose of the for loop means i
goes from 0 to 4. Which it does.
The issue is once i
gets to the last element of the list I get a error saying
Reference not set to an instance of an object. Aka nullreferenceException If I remember correctly.
I went to debugging and saw that all 5 elements of the list were not null and all was well and that the index is never out of range. So I am lost and I dont know why my code breaks when attempting to access the last element of the list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getChildat(index)
方法只能访问listView
的可见元素。在for循环中尝试一下:The
GetChildAt(index)
method can only access visible elements of theListView
. Try this in the for loop: