B4J Question Scroll to treeview item?

Mashiane

Expert
Licensed User
Hi there

B4X:
Sub TreeViewSetItem(tv As TreeView, s As String)
    Dim ti As TreeItem
    ti = TreeViewSearch(tv.Root, s)
    If ti.IsInitialized = True Then
        Dim jo As JavaObject = tv
        jo.RunMethodJO("getSelectionModel", Null).RunMethod("select", Array(ti))
    End If   
End Sub

Sub TreeViewSearch(Parent As TreeItem, s As String) As TreeItem
   For Each ti As TreeItem In Parent.Children
     If ti.Text = s Then
       Return ti
     End If
     If ti.Children.Size > 0 Then
       Dim res As TreeItem = TreeViewSearch(ti, s)
       If res.IsInitialized Then Return res
     End If
   Next
   Dim res As TreeItem
   Return res
End Sub
This managed to search for a tree item using the text value and also select it, how can I get the treeview to scroll and show the item?

Thanks
 

Erel

Administrator
Staff member
Licensed User
You can use this code to scroll to a TreeItem:
B4X:
Sub ScrollToItem (tree As TreeView, ti As TreeItem)
   Dim p As TreeItem = ti.Parent
   Do While p.Root = False
     p.Expanded = True
     p = p.Parent
   Loop
   Dim index As Int = CountVisibleChildren(tree.Root, ti, Array As Boolean(False))
   Dim jo As JavaObject = tree
   Log(index)
   jo.RunMethod("scrollTo", Array(index))
End Sub

Sub CountVisibleChildren(ti As TreeItem, Target As TreeItem, Found() As Boolean) As Int
   Dim c As Int = 1
   If ti = Target Then
     Found(0) = True
     Return -1
   End If
   If ti.Expanded Then
     For Each child As TreeItem In ti.Children
       c = c + CountVisibleChildren(child, Target, Found)
       If Found(0) = True Then Return c
     Next
   End If
   Return c
End Sub
Example:
B4X:
Sub MainForm_MouseClicked (EventData As MouseEvent)
   ScrollToItem(TreeView1, Search(TreeView1.Root, "56"))
End Sub
 
Top