5

I'm using Xamarin Android and I'm trying to change the ImageView src dynamically. All the pictures are placed in Resource/drawable. After reading the picture name as string from an xml (string imgName = nameFromXml + ".jpg") I would like to passing it to my ImageView. I guess there are two good ways:

1) Get the image (int)id and passing it to the ImageView using SetImageResource(): myTextView.SetImageResource(????????);

2) Get the Uri of the of the Image

EDIT
Unfortunately I couldn't use Eric answer for QuinDa question because there are many methods not existing on Xamarin Android, working just in Android.

Community
  • 1
  • 1
Masciuniria
  • 174
  • 1
  • 3
  • 10

5 Answers5

9

Here is the standard Android method:

int resImage = getResources().getIdentifier(imgName , "drawable", getPackageName());
myTextView.setImageResource(resImage);

Please note that imgName variable must not contain file extension.

Xamarin.Android C#:

int resImage = Resources.GetIdentifier(imgName, "drawable", PackageName);
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • Yes, I've already tryied this way but `resImage` is always 0. – Masciuniria Oct 09 '16 at 12:19
  • 1
    I've found another way: `int resourceId = (int)typeof(Resource.Drawable).GetField("myImageName").GetValue(null);` then, just: `imageView.SetImageResource(resourceId);` – Masciuniria Oct 09 '16 at 12:28
  • I have also noticed that the image does not get picked up when the name contains a capital letter, make sure all the text is lowercase. – Christo Nel May 22 '18 at 07:33
  • and what if we have 2 drawables with the same name and different extension? we can have an image.jpg and an vector image.xml – CDrosos Feb 22 '20 at 09:34
4

Thanks to SushiHangover and Romuald for their answer, but I'd like to share another way that I tested and it looks working well.

Here's how I get the id of the resource:

int resourceId = (int)typeof(Resource.Drawable).GetField("myImageName").GetValue(null);

So, then I'm able to use the normal SetImageResource():

imgViewCondition.SetImageResource(resourceId);
Masciuniria
  • 174
  • 1
  • 3
  • 10
2

The following code snippet solves the issue:

int id = getResources().getIdentifier("XXX", "drawable", getPackageName());
imageView.setImageResource(id);
Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
2

Just this:

FindViewById<ImageView>(Resource.Id.imageviewName).SetImageResource(Resource.Drawable.nameofimage);
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
Juan
  • 31
  • 1
2

I know it's an old question, but it never hurt to help.

The image should be stored in all the proper sizes for android inside the Resources Folder (drawable-hdpi, drawable-ldpi ....)

and then you get it dynamically like so

imageView.SetImageResource(Resource.Drawable.YourImageNameHere);
Leo Jebran
  • 154
  • 8