B4J Question Treeview.multiselect - there must be an easier way

johnmie

Active Member
Licensed User
Longtime User
My USB-Stick catalogue app contains a standard treeview of folders and files with options to view, delete or move files. This works fine when selecting a single entry, but with multiple selections (with ctrl or shift) it gets very complicated.

For now I use a workaround with two maps + last and previously selected items, but there must be an easier way (e.g. with JavaObject - selected.items as list or array), but I don't know how.

Can you help me? Many thanks in advance.
john m.
 

Chris2

Active Member
Licensed User
Longtime User
There may be other/better ways but when using a TreeView to make selections I use CheckboxTreeItems.

B4X:
TreeView.SetCheckBoxesMode

For Each ParentName as String in ParentNames 'ParentNames is a list'

    Dim pItem As CheckboxTreeItem
    pItem.Initialize("pi", ParentName)
   
    For Each ChildName as String in ChildNames 'ChildNames is a list'

        Dim cItem As CheckboxTreeItem
        cItem.Initialize("ci", ChildName)
        pItem.Children.Add(cItem)
   
    Next

   TreeView.Root.Children.add(pItem)

Next

Then use a B4XSet to store the selections in the ci_CheckedChange event
B4X:
Private Sub ci_CheckedChange(checked As Boolean)  
   
    Dim cti As CheckboxTreeItem = Sender
    If checked Then
        setCheckedItems.Add(cti.Text)
    Else
        If setCheckedItems.Contains(cti.Text) Then setCheckedItems.Remove(cti.Text)
    End If

End Sub

[untested code typed on the fly!]
 
Upvote 0

johnmie

Active Member
Licensed User
Longtime User
Thanks, Chris2 for your feedback.
since I already found (on the forum) items like
  • jo.RunMethodJO("getSelectionModel", Null).RunMethod("clearSelection", Null) and
  • jo.InitializeStatic("java.io.File").RunMethod("listRoots", Null)
I was convinced there was also a Java RunMethod to list all the selected rows. But which?
 
Upvote 0

Chris2

Active Member
Licensed User
Longtime User
My knowledge of JavaObject is limited, but based on this and this, try these:
B4X:
jo.RunMethodJO("getSelectionModel", Null).RunMethod("getSelectedItems", Null)
jo.RunMethodJO("getSelectionModel", Null).RunMethod("getSelectedIndices", Null)
[I'm sure there's someone out there who will correct this if it's wrong]
 
Upvote 0

johnmie

Active Member
Licensed User
Longtime User
I knew there is a better way, thank you for pointing in the right direction!
"getSelectedItems" did it and saved about 80 lines of code and on top of it I can use it on two different Treeviews (see code below).

Sub SelList(TW As TreeView)
selectedList.initialize
Dim jo As JavaObject = TW
selectedList = jo.RunMethodJO("getSelectionModel", Null).RunMethod("getSelectedItems", Null)
For i = 0 To selectedList.Size-1
Log(selectedList.Get(i).As(TreeItem).text)
Next
End Sub

Best, john m.
 
Upvote 0
Top