How to change the background of a button

dreamworld

Active Member
Licensed User
Longtime User
The follow codes do not work. When I pressed on the button, its background color did not change at all.

Sub Globals
Dim b As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
Dim cd(3) As ColorDrawable
cd(0).Initialize(Colors.Gray, 5)
cd(1).Initialize(Colors.Blue, 5)
cd(2).Initialize(Colors.Yellow, 5)
Dim sld As State ListDrawable
sld.Initialize
sld.AddState(sld.State_Enabled,ys(1))
sld.AddState(sld.State_Pressed,ys(2))
sld.AddCatchAllState(ys(0))
b.Initialize ("b")
b.Background = sld
Activity.AddView (b,0,0,100,45)
End Sub
 

Geezer

Active Member
Licensed User
Longtime User
The follow codes do not work. When I pressed on the button, its background color did not change at all.

B4X:
Sub Globals
   Dim b As Button 
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Dim cd(3) As ColorDrawable 
   cd(0).Initialize(Colors.Gray, 5)
   cd(1).Initialize(Colors.Blue, 5)
   cd(2).Initialize(Colors.Yellow, 5)
   Dim sld As State ListDrawable
   sld.Initialize
   sld.AddState(sld.State_Enabled,ys(1))
   sld.AddState(sld.State_Pressed,ys(2))
   sld.AddCatchAllState(ys(0))
   b.Initialize ("b")
   b.Background = sld
   Activity.AddView (b,0,0,100,45)
End Sub

Your code is almost correct, consider the differences...

B4X:
sld.AddState(sld.State_Disabled ,cd(0))
sld.AddState(sld.State_Pressed,cd(2))
sld.AddCatchAllState(cd(1))

You need to remove the Enabled state as that will be captured by the All State catch.

So, add the state to show when disabled, and pressed ... the default ( enabled ) will be show for the all state.
 
Upvote 0

dreamworld

Active Member
Licensed User
Longtime User
It works now. Thank you so much.
But I wrote the codes according to the example in B4A, so I think that B4A needs to improve itself.
 
Upvote 0
Top