Android Question Is it possible to choose a label programmatically?

Massy

Member
Licensed 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
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
 

sorex

Expert
Licensed 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
 

DonManfred

Expert
Licensed 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
 

sorex

Expert
Licensed 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
 

DonManfred

Expert
Licensed 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
 

sorex

Expert
Licensed 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.
 

klaus

Expert
Licensed 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
 
Top