Android Code Snippet Subs to Move or Swap List Items

I use Lists a lot and discovered there were no built-in methods to Move an item from one index location to another index location, and there is no method to Swap two items.

ListMoveItem(List, FromIndex, ToIndex)
Purpose: Move an existing item to a different location in a List.

Example:
ListMoveItem(List1, 4, 1) 'Move item at index 4 to index 1
'Note: The item that was at index 1 will be at index 2 after the move completes.​

ListSwapItems(List, Index1, Index2)
Purpose: Swap the item at Index1 with the item at Index2 in List.

Example:
ListSwapItems(List, 4, 1) 'Swap the item at index 4 with the item at index 1
A sample program is included.
 

Attachments

  • ListMoveSwapItems.zip
    9.1 KB · Views: 456

ddk1

Member
Licensed User
Thanks Widget, I was just doing some list moves yet again and thought I should write a reusable proc, and voila, you have already done and shared. Works perfectly, thanks.
 

GeoT

Active Member
Licensed User
Hi.
I think that ListMoveItem(List, FromIndex, ToIndex) movement function does not work well for all movement cases.
It is better, for example:

B4X:
Sub ListMoveItem(aList As List, aFromIndex As Int, aToIndex As Int)

        ' local variables
        Private i As Int = aFromIndex
       
        Private locObject As Object
        locObject = aList.Get(aFromIndex)
       
        ' move element down and shift other elements up
        If (aFromIndex < aToIndex) Then
            Do While (i < aToIndex)
                aList.Set(i, aList.Get(i+1))
                i = (i + 1)
            Loop
           
        End If
       
        ' move element up and shift other elements down
        Do While (i > aToIndex)
            aList.Set(i, aList.Get(i-1))
            i = (i - 1)
        Loop
       
        ' put element from position 1 to destination
        aList.Set(aToIndex, locObject)
End Sub

Greetings.
 
Top