I have an array declared as a button. I set the properties of the button in a loop and add them to a view. I need to know which button is pressed. How do I do this?
Here is my code:
B4X:
Sub declareBtn
Dim btn(10) As Button
pnlList.Initialize("")
For i = 0 To 9
btn(i).Initialize("btn")
btn(i).Text = "btn" + i
btn(i).TextColor = Colors.White
pnlList.AddView(btn(i),10,10 + (i * 50),280,50)
End If
Next
end sub
Sub btn_Click()
'In here, I need to know which button is pressed.
End Sub
Sub declareBtn
Dim btn(10) As Button
For i = 0 To 9
btn(i).Initialize("btn")
btn(i).Text = "btn" & i '!!! original code btn(i).Text = "btn" + i raised error ....
btn(i).TextColor = Colors.White
btn(i).Tag = i ' set button number to tag property ..
pnlList.AddView(btn(i),10,10 + (i * 50),280,50)
Next
End Sub
Sub btn_Click()
'Using Sender we find the button that raised this event
Dim b As Button
b = Sender
Log (b.Tag) 'can also use ... If b.Text = "btn2" Then (and do away with the Tag property)
End Sub
Sub declareBtn
'Dim btn(10) As Button
Dim btn as Button
For i = 0 To 9
btn.Initialize("btn")
btn.Text = "btn" & i '!!! original code btn(i).Text = "btn" + i raised error ....
btn.TextColor = Colors.White
btn.Tag = i ' set button number to tag property ..
pnlList.AddView(btn,10,10 + (i * 50),280,50)
Next
End Sub
Sub btn_Click()
'Using Sender we find the button that raised this event
Dim b As Button
b = Sender
Log (b.Tag) 'can also use ... If b.Text = "btn2" Then (and do away with the Tag property)
End Sub
why you use Dim btn(10) ???
is correct my example?
No, your example is not correct.
You must Dim the buttons inside the For / Next loop !
B4X:
Sub declareBtn
'Dim btn(10) As Button
For i = 0 To 9
Dim btn as Button
btn.Initialize("btn")
btn.Text = "btn" & i '!!! original code btn(i).Text = "btn" + i raised error ....
btn.TextColor = Colors.White
btn.Tag = i ' set button number to tag property ..
pnlList.AddView(btn,10,10 + (i * 50),280,50)
Next
End Sub
The advantage of Dim btn(10) As Button is that you can access each button anywhere in the code like btn(2).Text = "New text".
If you dont need to access any of the buttons in the code your example is simpler.