Android Question Is it possible to choose a label programmatically?

Massy

Member
Licensed User
Longtime User
Let's say I have 10 labels named "label0", "label1" and so on... and a list with 10 strings "listNames(10) As String" and I want programmatically send the 10 strings that are in the list at every label depending on their name...
is it possible to shorten the code doing something like this?:

For i = 0 To 9
label(i).text = listNames(i)
Next

Thansk for any help
Massy
 

imbault

Well-Known Member
Licensed User
Longtime User
You should do that :
B4X:
Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim Label() As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
Dim Label(10) As Label
For i = 0 To 9
    Label(i).Initialize("")
    Label(i).text = listNames(i)
    Activity.AddView(Label(i),0dip,(i+1)*10dip,350dip,10dip)
Next

End Sub
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
if you give them a tag value like label0 label1 etc you could run through all the views and check if the tag equals the loop value and set the text if needed.

this works for both designer or scripted added views.

search for getallviewsrecursive
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Put your 10 labels into a list a list after you have loaded the layout

B4X:
Dim Label(10) As Label
Label(0) = lblxy1
Label(1) = lblxxx
Label(2) = lbltest
[...]

then you can use something like
B4X:
For i = 0 To 9
    dim lbl As Label = Label(i)   
    lbl.text = listNames(i)
Next
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
not sure if this works but it will be close
B4X:
for x=0 to 9
setLabelText("label"&x,labeltexts(x))
next

sub setLabelText(lTag as string,lText as string)
 For Each v As View In pnlLabels.GetAllViewsRecursive
  If v.tag=lTag Then v.text=lText
 Next
end sub
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Better check it it is really a label...
And you need to bind the "v" to an objectinstance (dim)
B4X:
sub setLabelText(lTag as string,lText as string)
For Each v As View In pnlLabels.GetAllViewsRecursive
if v is Label then
    dim lbl as Label = v
    If v.tag=t Then  v.text=lText
    Next
end if
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
I don't use the label check since I don't tag an image with label or lbl ;)

but you're right for the dim, otherwise it doesn't know it has that property.
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
As the Labels already exist, I would do it that way:
B4X:
Dim Labels(10) As Label
Labels = Array As Label (label0, label1, label2, label3, label4, label5, label6, label7, label8, label9)
For i = 0 To 9
  Labels(i).text = listNames(i)
Next
 
Upvote 0
Top