Android Question CustomListView - bug in getLastVisibleIndex?

Misterbates

Active Member
Licensed User
The current code tests bottom against ScrollPosition + Height with bottom starting from 0:
B4X:
'Gets the index of the last visible item.
Public Sub getLastVisibleIndex As Int
    Dim first As Int = getFirstVisibleIndex
    Dim bottom As Int
    For i = first To items.Size - 1
        bottom = bottom + heights.Get(i) + dividerHeight
        If bottom >= sv.ScrollPosition  + sv.Height Then Return Max(i - 1, first)
    Next
    Return items.Size - 1
End Sub

It seems that the test, if i starts at FirstVisibleIndex, should be against the height of the visible items, as follows:
B4X:
'Gets the index of the last visible item.
Public Sub getLastVisibleIndex As Int
    Dim first As Int = getFirstVisibleIndex
    Dim bottom As Int
    For i = first To items.Size - 1
        bottom = bottom + heights.Get(i) + dividerHeight
        If bottom >= sv.Height Then Return Max(i - 1, first)
    Next
    Return items.Size - 1
End Sub
 

Misterbates

Active Member
Licensed User
Attached. In the top CustomListView on my device I see items 26-30 (and the divider between 25 and 26). In the log I see First=25, Last=49. Which raises the question, should FirstVisibleItem be returning the actual first visible item, rather than the divider between items?
 

Attachments

  • LastVisibleItemBug.zip
    12.2 KB · Views: 192
Upvote 0

Misterbates

Active Member
Licensed User
You are seeing items 25-29. Remember that the index of the first item is 0.

To make it more clear, change your code to:
B4X:
For i = 0 To 50
   clv1.AddTextItem(i, i)
Next
Gotcha.

But what about the bug? LastVisibleItem reports 49 (in the log) when items 25-29 are displayed?
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
The correct code should be:
B4X:
Public Sub getLastVisibleIndex As Int
   Dim first As Int = getFirstVisibleIndex
   Dim bottom As Int
   For i = 0 To items.Size - 1
     bottom = bottom + heights.Get(i) + dividerHeight
     If i >= first And bottom >= sv.ScrollPosition  + sv.Height Then Return Max(i - 1, first)
   Next
   Return items.Size - 1
End Sub

I will post the updated library.
 
Upvote 0
Top