B4J Question Reference an object with a variable or string

Kintara

Member
Licensed User
Longtime User
This also applies to B4A

In B4PPC I was able to use a string and / or variable to refrence a control.

e.g.

to colour Button0, Button1, Button2 & Button3 red I used something like:
For i = 0 to 3
Control("Button" & i ).color=cRed
Next

What is the equivalent to Control() in B4A and B4J?

Thanks


Kintara
:cool:
 

LucaMs

Expert
Licensed User
Longtime User
I don't know B4PPC, so i don't know Control. Is it a Keyword and then a Function that "works" everywhere? Simply passing the name of a... control to it?
If it is so, in B4A it does not exists, because... controls (views) have no name! (daaamn).

But you can use something like this :(:

B4X:
    ' You must set Button1.Tag = "Button1". For each Button, obviously.
    Dim Obj As Object
    For I = 0 To Activity.NumberOfViews - 1 ' or Panel1.NumberOfViews if buttons are in a panel.
        Obj = Activity.GetView(I)
        If GetType(Obj) = "android.widget.Button" Then
            Dim btn As Button
            btn = Obj
            Dim strTag As String = btn.Tag
            If strTag.StartsWith("Button") Then
                btn.Color = Colors.Red
            End If
        End If
    Next

You could put ALL THIS :( in a Sub named "Control" in a Code Module (using appropriate parameters), so you can call it using one line only
 
Last edited:
Upvote 0

Kintara

Member
Licensed User
Longtime User
Thank you for that, its something I'll try.
I was hoping to use it in a Sub called LoadTableFromCSV ( TableName As String,Dir As String, Filename As String, Headers As Boolean) but could not get the variable 'TableName' to work in lines of code like TableName.Items.Clear as there does not seem to be an easy way to replicate the B4PPC code of Control(TableName).Items.Clear where the variable TableName is given the value "Table1" so it will clear the Tableview called "Table1".

Hope that makes sense.

Kinata :cool:
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
If you pass TableName as a TableView you can refer to it in the sub by TableName
eg
B4X:
Sub called LoadTableFromCSV ( TableName As TableView,Dir As String, Filename As String, Headers As Boolean) 
TableName.Items.Clear
...
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
As @Daestrum answered you should just pass the object instead of the variable name.

If you really want to map objects to strings then you can use a Map to do it:
B4X:
Dim mapOfViews As Mp
mapOfViews.Initialize
mapOfViews.Put("Button1", Button1)
mapOfViews.Put("Button2", Button2)
...

Dim b As Button = mapOfViews.Get("Button5")
b.Text = "..."
 
Upvote 0
Top