Home > Back-end >  How to Random Images with delay in a secs in Xamarin Forms and Display into XAML?
How to Random Images with delay in a secs in Xamarin Forms and Display into XAML?

Time:10-29

I want to random images and implement delays in a seconds in xamarin forms.

This is my XAML Code

<Image x:Name="RandomImageList" Source="Album1.jpg">

This is my C# Code

List<string> imageList = new List<string> { "Album1.jpg", "Album2.jpg", "Album3.jpg" };

        var random = new Random();
        var next = random.Next(4);
        var image = imageList[next];

        RandomImageList.Source = ImageSource.FromResource(image);

And this is the result during i run this code.

*System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.' *

CodePudding user response:

It's easy, just do this.

public MainPage()
{
    InitializeComponent();

    List<string> imageList = new List<string> { "add.png", "compare.png", "down.png", "remove.png" };

    Device.BeginInvokeOnMainThread(async () =>
    {
        while (true)
        {
            var random = new Random();
            var next = random.Next(4);
            var image = imageList[next];
            await Task.Delay(2000);

            RandomImage.Source = ImageSource.FromFile(image);
        }
    });
}

Output:

enter image description here

  • Related