Android Question Adding buttons to a panel

apty

Active Member
Licensed User
Longtime User
I am looking for a way of adding 10 buttons to a panel programmatically. Each of these buttons when clicked will have its own functionality. Is it possible to do this without using the AHDashboard library?

I have been doing it as below but this process is not efficient if i want, say 20 buttons.

B4X:
btn1.Initialize("Button1")
    btn1.Text="Button1"
    btn2.Initialize("Button2")
    btn2.Text="Button2"
    btn3.Initialize("Button3")
    btn3.Text="Button3"
    btn4.Initialize("Button4")
    btn4.Text="Button4"
    pnl1.Initialize("")
    pnl1.Color=Colors.Transparent
    pnl1.AddView(btn1,25%x-50dip,20%y,100dip,100dip)
    pnl1.AddView(btn2,75%x-50dip,20%y,100dip,100dip)
    pnl1.AddView(btn3,25%x-50dip,60%y,100dip,100dip)
    pnl1.AddView(btn4,75%x-50dip,60%y,100dip,100dip)
    Activity.AddView(pnl1,0dip,0dip,100%x,100%y)
 

MaFu

Well-Known Member
Licensed User
Longtime User
B4X:
    Dim pnl1 As Panel
    pnl1.Initialize("")
    pnl1.Color = Colors.Transparent
    Dim btn(4) As Button
    Dim posX(4) As Int = Array As Int(25%x, 75%x, 25%x, 75%x)
    Dim posY(4) As Int = Array As Int(20%y, 20%y, 60%y, 60%y)
    For i = 0 To 3
        btn(i).Initialize("Button")  'all buttons use same event sub
        btn(i).Tag = i  'to distinguish the buttons in event sub
        btn(i).Text = "Button" & (i + 1) 'or use a string array like posX/posY
        pnl1.AddView(btn(i), posX(i) - 50dip, posY(i), 100dip, 100dip)
    Next
    Activity.AddView(pnl1, 0dip, 0dip, 100%x, 100%y)
 
Upvote 0

apty

Active Member
Licensed User
Longtime User
Could this part
B4X:
Dim posX(4) As Int = Array As Int(25%x, 75%x, 25%x, 75%x)
    Dim posY(4) As Int = Array As Int(20%y, 20%y, 60%y, 60%y)
also be automatically generated e.g if i have 20 buttons?
 
Upvote 0

James Chamblin

Active Member
Licensed User
Longtime User
B4X:
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 pnl1 As Panel
    Dim Rows, Columns As Int
    pnl1.Initialize("")
    pnl1.Color = Colors.Transparent
    Activity.AddView(pnl1,0,0,100%x,100%y)
   
    If 100%x > 100%y Then 'landscape
        Rows = 5
        Columns = 4
    Else 'portrait
        Rows = 4
        Columns = 5       
    End If
   
    Dim BWidth As Int = 100%x / Columns
    Dim BHeight As Int = 100%y / Rows
   
    Dim x, y As Int
    For y = 0 To Rows - 1
        For x = 0 To Columns - 1
            Dim bt As Button
            bt.Initialize("Button")
            bt.Text = "Button"&(x+y*Columns)
            bt.Tag = "Button"&(x+y*Columns)
            pnl1.AddView(bt,x*BWidth+2dip,y*BHeight+2dip,BWidth-4dip,BHeight-4dip)
        Next           
    Next
   
End Sub

Sub Button_Click
    Dim bt As Button = Sender
    ToastMessageShow("You Pressed Button "&bt.Tag,False)
End Sub
 
Upvote 0
Top