B4J Tutorial String to variable - Iterate variable names

This is a simple idea to replace the function "eval" or "execute" that other programming languages have. The purpose is to retrieve a variable from a string:

How to iterate variable names:
B4X:
Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("layout") 'Load the layout file.
    MainForm.Show

    'Set the tag of each button to the variable name:
    btn1.Tag = "btn1"
    btn2.Tag = "btn2"
    btn3.Tag = "btn3"

    'Now you can iterate through the buttons this way:
    For i = 1 To 3
        StringToButton("btn" & i).Text = "Hello"
    Next
End Sub

Sub StringToButton(Eval As String) As Button
    Dim b As Button
    For Each n As Node In MainForm.RootPane.GetAllViewsRecursive
        If n.Tag = Eval Then
            b = n
            Return b
        End If
    Next
    Return b
End Sub

Of you you will need to adapt this script to your project. For example, if you are looking for a label, then the function should return a label.
 
Top