0

I would like to set ImageView resource from string dynamically, but I could not do that with following method.

I am using Xamarin/Android to set ImageView resource dynamically as below;

ImageView homeItemImage = convertView.FindViewById<ImageView>(Resource.Id.homeItemImage);
int imageId = PlatformProvider.GetImageId(Context, contentTitle.IconImageUrl);
homeItemImage.SetImageResource(imageId);

GetImageId function:

public static int GetImageId(Context context, string imageName)
{
//   int identifier = context.Resources.GetIdentifier(imageName, "drawable", context.PackageName);
int identifier = context.Resources.GetIdentifier(context.PackageName + ":drawable/" + imageName, null, context.PackageName);
return identifier;
}

I am passing imageName both wasy as "Account.png" or "Account" both returns int as 0.

enter image description here

enter image description here

Here is my image folder:

qqq

And I set them up as AndroidResource (here is shows About.png but Account.png is same way):

qqq

They show in intellisense:

qqq

How can I set image source from string?

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158

1 Answers1

0

Ressources must not contains special character ->

Each file inside folder is translated into java field name inside R.java class:

drawable\icon.png -> R.drawable.icon Hence the reason for not using special characters inside file names, as they can no be used in Java names.

As for capital letters, I guess that's to avoid one little problem in Windows vs. Linux environment. That's because Linux thinks that Icon.png and icon.png are different files, and Windows thinks that Icon.png and icon.png is the same file. So anyone using Linux can create application that is not compilable on Windows.

Community
  • 1
  • 1
Jaythaking
  • 2,200
  • 4
  • 25
  • 67
  • Yeah, this is first option I tried; context.Resources.GetIdentifier(imageName, "drawable", context.PackageName); and it still returns 0 all the time. – Teoman shipahi Sep 12 '16 at 15:34
  • but why you are doing context.Ressources instead of context.getRessources() ? – Jaythaking Sep 12 '16 at 15:35
  • You mean context.PackageName? It is Xamarin implementation over Android and I checked it returns correct package name. – Teoman shipahi Sep 12 '16 at 15:36
  • Yeah you are right, have you try without Capital Letter? It might causes the issue as it's a special character. Related to this-> http://stackoverflow.com/questions/6758228/why-cant-file-names-in-the-drawable-folder-contain-special-characters-or-start – Jaythaking Sep 12 '16 at 15:40
  • This explains the weirdness more clearly, thanks. – Teoman shipahi Sep 12 '16 at 15:56