Problem with add view to RelativeLayout in loop

tigerigortigerigor Member ✭✭

Good day!

I have some strange problem with code (I put only important lines here):

...
RelativeLayout r;
Image[] ims
...

{
r = FindByName("relforimages");
float width = 400f, height = 300f;
ims = new Image[2];

for (int i = 0; i < 2 ; i++) {
ims[i] = new Image {
Aspect = Aspect.AspectFit,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
ims[i].Source = ImageSource.FromFile(localPathyn);
r.Children.Add(ims[i], ()=> new Rectangle(width * i * 0.1f,
height * i * 0.1f,
70f, 70f));
}

After this I see only last image in RelativeLayout. Even I increase count of images to 10 (for example) nothing happens - i see only LAST image

Question: is it possible (in xmarin) to use array element for add view to layout dynammically? if it's possible - what is mistake i do?

Tagged:

Best Answer

  • LandLuLandLu Xamurai
    Accepted Answer

    Adjust your code like:

    r = FindByName("relforimages") as RelativeLayout;
    float width = 400f, height = 300f;
    ims = new Image[2];
    
    for (int i = 0; i < 2; i++)
    {
        ims[i] = new Image
        {
            Aspect = Aspect.AspectFit,
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        };
        ims[i].Source = ImageSource.FromFile(localPathyn);
    
        var rectangle = new Rectangle(width * i * 0.1f, height * i * 0.1f, 70f, 70f);
        r.Children.Add(ims[i], () => rectangle);
    }
    

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai
    Accepted Answer

    Adjust your code like:

    r = FindByName("relforimages") as RelativeLayout;
    float width = 400f, height = 300f;
    ims = new Image[2];
    
    for (int i = 0; i < 2; i++)
    {
        ims[i] = new Image
        {
            Aspect = Aspect.AspectFit,
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        };
        ims[i].Source = ImageSource.FromFile(localPathyn);
    
        var rectangle = new Rectangle(width * i * 0.1f, height * i * 0.1f, 70f, 70f);
        r.Children.Add(ims[i], () => rectangle);
    }
    
Sign In or Register to comment.