Android Question Arrays of views question

Tim Green

Member
Licensed User
Longtime User
Using "Android Tutorial Tick-Tack-Toe: working with arrays of views" as a code model I implemented a simple application which creates a 5x5 matrix of small panels on the screen and then sets the color of one of the panels. But as detailed in the uploaded application, the last created panel seems to be referenced whenever any of the other panels is referenced.

I found a hack workaround for this issue but still do not understand the cause. Can anyone explain what is happening here?

I suspect it is an object instantiation issue or timing but I am not sure.

Sub Activity_Create(FirstTime As Boolean)

Activity.LoadLayout( "Mystery" )

Dim Y As Int
Dim X As Int

Dim cdw As ColorDrawable
cdw.Initialize2( Colors.LightGray, 25dip, 1dip, Colors.White ) ' Color, Radius, BorderWidth, ColorBorder

For Y = 0 To 4
For X = 0 To 4
Dim New_Thing As Panel
New_Thing.Initialize( "panel" )
New_Thing.Background = cdw
Activity.AddView( New_Thing, ( X * 60dip ) + 10dip, ( Y * 60dip ) + 10dip, 50dip, 50dip )
Things( X, Y ) = New_Thing ' Save reference to this thing
Next
Next

' Mystery issue: When changing the color of any selected Things( X, Y )
' the color of the last created Things( 4, 4 ) also changes.

' Hack solution: Add a final "dummy" panel which will hide the mystery issue:

' New_Thing.Initialize( "panel" )
' New_Thing.Background = cdw
' Activity.AddView( New_Thing, 0dip, 0dip, 50dip, 50dip )
' New_Thing.Enabled = False
' New_Thing.Visible = False

DoEvents ' Without this all Things change color below

Things( 2, 3 ).Color = Colors.Red

' It is obvious that Things( 4, 4 ) and New_Thing are referencing the same object.
' But do not understand why changing the color of Things( 2, 3 ), which should be
' a different instance, would affect the color of New_Thing or Things( 4, 4 ).

End Sub
 

Attachments

  • Mystery.zip
    6.9 KB · Views: 109

klaus

Expert
Licensed User
Longtime User
Use this:
B4X:
For Y = 0 To 4
   For X = 0 To 4
     Dim cdw As ColorDrawable
     cdw.Initialize2( Colors.LightGray, 25dip, 1dip, Colors.White )   ' Color, Radius, BorderWidth, ColorBorder
     Things(X, Y).Initialize( "Things" )
     Things(X, Y).Background = cdw
     Activity.AddView( Things(X, Y), ( X * 60dip ) + 10dip, ( Y * 60dip ) + 10dip,  50dip, 50dip )
   Next
Next
You need to Dim and Initialize cdw inside the For / Next loop.
 
Last edited:
Upvote 0

Tim Green

Member
Licensed User
Longtime User
Thanks Klaus. Moving the dim and initialize of the ColorDrawable works fine.
I still do not have a deep understanding of the root cause but I can now at least use VB6-like arrays of displayed objects in my B4A code.
Thanks again.
 
Upvote 0
Top