toggled background color button

Barbadidoua

New Member
Licensed User
Longtime User
Hello,

I am almost beginner ...:sign0013:
After loading the image on a button, I want to toggle it's background color Green/Red each time the button is pressed : the image disapear :mad: !

Can someone help me ?

Here is my code:

Sub Globals
Dim btnF1 As Button
Dim bm1,bm2 As Bitmap
bm1.Initialize(File.DirAssets,"l.png")
End Sub

Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Main")
New
End Sub

Sub New()
btnF1.text="0"
btnF1.SetBackgroundImage(bm1)
End Sub

Sub btnF1_Click
If btnF1.text=0 Then
btnF1.Color = Colors.RGB(150,227,123)
btnF1.Text="1"
Else
btnF1.Color= Colors.RGB(245,93,47)
btnF1.Text="0"
End If
End Sub
 

alfcen

Well-Known Member
Licensed User
Longtime User
When setting a background color the image gets lost, you can however reload the image in the Button_Up event. Even better, use the Designer to configure your buttons. There you can define the 3 states of buttons without a line code.
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
The background of a ToggleButton is a StateDrawable.
A StateDrawable can be either:
- ColorDrawable
- GradientDrawable
- BitmapDrawable

The attached testprogram shows you how to do it for ColorDrawable and BitmapDrawable.
For more details you could have a look at chapter 9.1 View Drawables in the User's Guide.

Best regards.
 

Attachments

  • ToggleButton.zip
    8.7 KB · Views: 683
Upvote 0

JohnC

Expert
Licensed User
Longtime User
Thanks for the sample, but I am real confused about what this line does:

B4X:
states(1) = -sd.state_checked

Why the leading "-" minus sign?

Later in the code you are setting the "checked" state for the same button:

B4X:
    Dim states(1) As Int
    states(0) = sd.state_checked
    sd.AddState2(states, cdw2)

So, I don't understand what the first "-" line is doing..

Could you explain?
 
Upvote 0
Top