Reuse of same label appears to draw multiple time differently

JohnK

Active Member
Licensed User
Longtime User
I was planning on using an array of labels on my activity for different labels. However, when I copy-pasted the code, I forgot to change the array indexes, but the app still appeared to treat each call as a different label. Its done what I was planning on it to do, but it actually looks like it shouldn't be as I hadn't finished coding.

The code below is cut down, but its enough to get the gist

I was expecting to be passing in a different "Index" to each call to "AddLabel" (ie the first parameter), however, the first time I ran it (and ever since) I simply pass in Zero, and I get the two different labels? I would of expected the second call to invalidate / overwrite the first call.
B4X:
Sub Globals
   Dim lblLabel(10) As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
   AddLabel(0, 10, "Line 0")
   AddLabel(0, 100, "Line 1, but still using index 0!")
End Sub

Sub AddLabel(Index As Int, Y As Int, Text As String)
   lblLabel(Index).Initialize("")
   lblLabel(Index).Text = Text
   scvScroll.Panel.AddView(lblLabel(Index), 10, Y, Activity.width, 50) 
End Sub
I tried to cut the code down to the minimum.

Am I wrong in thinking that it shouldn't work?Is it safe to take advantage of this behavior?
 

thedesolatesoul

Expert
Licensed User
Longtime User
It depends on what you want to do, really.
This line:
B4X:
lblLabel(Index).Initialize("")
creates a new object.
Then you add it to the scrollview panel.

So now the scrollview panel has a reference to the object, and even when you create another object on the same array index, it does not destroy the first one.

However, now you will not be able to access all the other labels through lblLabel. Only the last label you added can be accessed through lblLabel(0).

It is safe to use this technique and sometimes it is the only way, when you need to re-use a structure to hold another object.
 
Upvote 0
Top