How to set string image name as image

orma2812orma2812 Member ✭✭
edited December 2018 in Xamarin.Android

Hello, I need to set a random image from a string array images names. How can I do that? I've already generated a random image name but can't set it as image
This is the code:

using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using System.Threading.Tasks;
using System;

namespace MemoryGame
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private Random rnd = new Random();
private ImageView mImage1;
private ImageView mImage2;

    public void SetData()
    {
        mImage1 = FindViewById<ImageView>(Resource.Id.backImage1);
        mImage2 = FindViewById<ImageView>(Resource.Id.backImage2);

        string[] images = { "banana", "basketball", "bomb", "cat", "dog", "human", "phone", "plane" };
        int mIndex = rnd.Next(images.Length);
        string resourceId = images[mIndex];

      // I tried to do it but not working
        mImage2.SetImageResource(resourceId);
    }

}

}

Best Answer

Answers

  • elvisonelvison Member ✭✭

    The argument for ImageView.SetImageResource() should be an integer which is the resource Id generated at build time.
    I think you should try something like this (if "banana" and "basketball" correspond to some drawables in Resources folder):

    public void SetData() 
    {
        int[] imageIds = { 
            Resource.Drawable.banana, 
            Resource.Drawable.basketball,
            Resource.Drawable.bomb,
            Resource.Drawable.cat
            // etc
        };
    
        // getting your index here
        // index = 0;
    
        mImage2.SetImageResource(imageIds[index]);
    }
    
Sign In or Register to comment.