8

I am using MonoDevelop for Android and i am trying to create a Drawable variable from an image in the resources folder.

I have the following files in my Resources\drawable folder:

Icon.png
monkey.png
monkeyPurple.png

How do I create a Drawable variable that has the image obtained from one of these files?

I have tried the following code:

Drawable icon = Drawable.CreateFromPath("Icon.png");

This however does not work. If this is the correct way to load an image from file, do I need to have the full filename and path to the file? I have tried many combinations to access the image, with no luck.

I have also tried the following:

Drawable icon = R.getResources().getDrawable(R.drawable.Icon); 
Drawable icon = R.getResources().getDrawable(R.drawable.monkey);

Also with no luck.

Can I please have some help in correctly creating a Drawable variable that has an image from the resource folder?

Thanks

Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100
Garry
  • 1,251
  • 9
  • 25
  • 45

2 Answers2

13

You're very close, but I think you're mixing Java and C#.

You can access this using the Resource structure. I've put both the Mono for Android and Java versions below for reference but in your case you want the C# version if you're using Mono for Android.

Mono for Android (C#)

Drawable icon = Resources.GetDrawable(Resource.Drawable.Icon);

Android SDK (Java)

Resources res = getResources();
Drawable icon = res.getDrawable(R.drawable.Icon);
Kirk
  • 16,182
  • 20
  • 80
  • 112
4

As of Android API version 21, the old method is deprecated and replaced by the following:

Drawable icon = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.Icon, null);

For more details check the original Android answer

Community
  • 1
  • 1
MujtabaFR
  • 5,956
  • 6
  • 40
  • 66