B4J Code Snippet Moving Cursor to end of text in TextField

Normally, moving the cursor to the end of a TextField is a one-liner:
B4X:
txfChanged.SetSelection(txfChanged.Text.Length, txfChanged.Text.Length)

But when you tab from TextField to TextField, inserting this into the _FocusChanged event doesn't work, and the field is left with all the text selected and the cursor blinking at the start of it. I believe this has something to do with the exact state of the textbox when the event execution has not yet been completed. I was surprised at how many people had questioned how to do this, and the convoluted solutions offered -but very few for B4J.
Here is some simple code I have found that works for me. Tested in B4J, haven't tested it in B4A.
B4X:
' Handle the FocusChanged event after the tab key has been pressed.
' The Event Name property in the Textfield is set to "txtField" in the designer.
Sub txtField_FocusChanged (HasFocus As Boolean)
   ' Setselection Won't work directly in this event.
   ' Call it in a separate one when the true focus state is complete.
   Dim txfToFocus As TextField = Sender
   If HasFocus Then CallSubDelayed2(Me, "txtField_FocusChanged2", txfToFocus)
End Sub
' Set the cursor at the end of the text
Sub txtField_FocusChanged2(txf As TextField)
   txf.SetSelection(txf.Text.Length, txf.Text.Length)
End Sub
Hope this can solve a problem for someone out there.
 
Top