ListView无法访问列表的最后元素

发布于 2025-02-11 11:22:20 字数 852 浏览 2 评论 0原文

我有一个要在屏幕上列出的对象列表,并使用带有适配器的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赠我空喜 2025-02-18 11:22:21

getChildat(index)方法只能访问listView的可见元素。在for循环中尝试一下:

for (int i = 0; i <= f_listView.getLastVisiblePosition() - f_listView.getFirstVisiblePosition(); i++)

The GetChildAt(index) method can only access visible elements of the ListView. Try this in the for loop:

for (int i = 0; i <= f_listView.getLastVisiblePosition() - f_listView.getFirstVisiblePosition(); i++)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文