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.
CodePudding user response:
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 )