Android Question Load designed imageview in an array

encol1000

New Member
Hello,
i'm trying to save all the activity's imageviews (generated by the designer) in an array (with their original position), but when i do it, all positions of the array point to the same object (a reference to the last view i get).

What am i wrong?


my code is:

B4X:
Sub Process_Globals
[...]
  Type Immagine(img As ImageView, OrigX As Int, OrigY As Int)
[...]
End Sub


Sub Globals
[...]
  Private Immagini(9) As Immagine
[...]
End Sub

Sub Activity_Create(FirstTime As Boolean)
[...]
        Dim i As Int
        Dim iv As Immagine
        i=0
        For Each v As ImageView In Activity.GetAllViewsRecursive
            If v Is ImageView Then
                iv.img=v
                iv.OrigX=v.Left
                iv.OrigY=v.top
                Immagini(i)=iv
                i=i+1
            End If
        Next   
[...]

Thanks in advance
 

udg

Expert
Licensed User
Longtime User
Hi,

move "Dim iv As Immagine" inside the For loop.
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
Yep.

Explanation: Dim creates exact ONE object. With "Immagini(i)=iv" you put the same object "iv" to it all the time. Because it's the SAME object you overwrite it with "v" and the last one will be there after the loop. If you dim again in your loop as udg said, it will be another object (same name).

At the end of the loop you will the have 10 objects "v" in the array (same name but 10 instances).
 
Upvote 0

encol1000

New Member
move "Dim iv As Immagine" inside the For loop.
I tried but the whole array still points to the same object :(

Another question: is the
B4X:
For Each v As Imageview...
correct?
In the activity I have also buttons and checkboxes
 
Upvote 0

encol1000

New Member
You need to move the Dim iv... to the For loop. It should work.
Moving the "Dim iv As Immagine" in the for doesn't work, but i changed my code in this way:

B4X:
[...]
For Each v As View In Activity.GetAllViewsRecursive         
        If v Is ImageView Then
            Dim iv As ImageView
                 
            iv=v
            Immagini(i).img=iv
            Immagini(i).OrigX=iv.Left
            Immagini(i).OrigY=iv.Top
[...]

and now it works! :D

It seems that type Immagine is created always as a reference, even if in the for
 
Last edited:
Upvote 0
Top