Android Question Address object by String

JayC

New Member
Licensed User
Longtime User
I 'm using the code below to change a Buttons background based on a given value, that is saved in it's in the .TAG
this is the code I'm using now to set the Buttons background. works fine.

B4X:
Sub changebitmap(b AsButton ) Dim i As indices
i = b.tag
i.Player = Player
Log("changeBitmap: X=" & i.x & " Y="& i.y & " Val="& i.Val & " Player=" & Player)
Select i.ValCase0
b.SetBackgroundImage(Image0)Case1If Player = 1Then
b.SetBackgroundImage(Image11)Else
b.SetBackgroundImage(Image21)EndIf Case2If Player = 1Then
b.SetBackgroundImage(Image12)Else
b.SetBackgroundImage(Image22)EndIfCase3If Player = 1Then
b.SetBackgroundImage(Image13)Else
b.SetBackgroundImage(Image23)EndIfCase4If Player = 1Then
b.SetBackgroundImage(Image14)Else
b.SetBackgroundImage(Image24)EndIf
CaseElse
b.SetBackgroundImage(Image5)EndSelect
End Sub

What I'd like to do, is use a string to call the image object something like this.

B4X:
dim strObj asstring
strImage = i.Val
player = i.player
strObj = "Image" & Player & strImage
b.SetBackgroundImage(strObj)
This would be simpler and would make it easier to add more players.

or, is there a way to set the Back ground image to, say 90%x,90%y of the Button. and then i would set to back ground color to the player's color. if i could, I would not have to load so many images.
 

LucaMs

Expert
Licensed User
Longtime User
You can use a map that has a number as key and a bitmap as value.

B4X:
Dim MyImages As Map
MyImages.Initialize
MyImages.Put(0, Image0)
MyImages.Put(11, Image11)
MyImages.Put(21, Image21)
'...

' then, calculate the key (index).
Dim key As Int

If i.val = 0 Then
    key = 0
Else
    key = i.val + player * 10
End If

b.SetBackgroundImage(MyImages.Get(key))
 
Last edited:
Upvote 0
Top