Android Code Snippet Subs to Move or Swap List Items

Discussion in 'Code Snippets' started by Widget, Feb 16, 2017.

  1. Widget

    Widget Well-Known Member Licensed User

    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.

    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.

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

    Attached Files:

    Almora, paragkini and RauchG like this.
  2. ddk1

    ddk1 New 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.
  3. GeoT

    GeoT Member Licensed User

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

    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+
                    i = (i + 
    End If
    ' move element up and shift other elements down
            Do While (i > aToIndex)
                aList.Set(i, aList.Get(i-
                i = (i - 
    ' put element from position 1 to destination
            aList.Set(aToIndex, locObject)
    End Sub
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice