Android Question trouble adding views to panels in a loop

Eric H

Active Member
Licensed User
Longtime User
I am expecting that this code should create 6 panels. each with a label on top indicating the panel number. However, when I run this code, all 6 panels are created just fine, but only the first label is created on the first panel, while the other 5 panels are just blank.



I'm sure I am just overlooking something simple.

B4X:
Sub Activity_Create(FirstTime As Boolean)
  
    'panel gradient setup
    Dim grPanel As GradientDrawable
        Dim grPanelColors(2) As Int
        grPanelColors(0) = Colors.RGB(25,25,25)
        grPanelColors(1) = Colors.RGB(50,50,50)
        grPanel.Initialize("BOTTOM_TOP", grPanelColors)
        grPanel.CornerRadius = 10dip      
      
    'create sound panels
    Dim spHeight As Int = 80dip
    For i = 0 To 5
        Dim p As Panel
        p.Initialize("")
        p.Background = grPanel
        p.Tag = ("p" & i)
        Log("Panel " & p.Tag & " loaded")
        Activity.AddView(p, 0, spHeight * i, Activity.Width, spHeight)
      
        ' create a label for the panel
        Dim l As Label
        l.Initialize("")
        l.TextSize = 24
        l.Tag = ("l" & i)
        l.Gravity = Gravity.CENTER_HORIZONTAL
        l.Text = ("Panel " & i)
        Log("Label " & l.Tag & " loaded")
        p.AddView(l, p.Left, p.Top, p.Width, 30dip)
    Next
      
End Sub

Anyone able to spot my mistake?

Also, I haven't gotten there yet, but I am assuming to detect which panel's child view triggered an event I will just set the 'sender' equal to the view's tag, right?

Thanks.
Eric H
 

LucaMs

Expert
Licensed User
Longtime User
p.top increases each time, the label "drops" and is covered.

B4X:
'    p.AddView(l, p.Left, p.Top, p.Width, 30dip)
p.AddView(l, p.Left, 2dip, p.Width, 30dip)

You shoud initialize each panel with the same event name.
p.Initialize("MyPanel")
Then:
B4X:
Private Sub MyPanel_Click
    Dim SelectedPanel As Panel = Sender
End Sub

You can also use the same name for the event of the label and then identify the type of sender:
B4X:
Private Sub MyPanel_Click
    If Sender Is Panel Then
        Log("Panel")
        Dim pnl As Panel = Sender
    Else
        Log("Label")
        Dim lbl As Label = Sender
    End If
End Sub
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…