It’s no secret that we can not access Image Resources by name in Android specially in code behind, whereas you need to pass in the Resource ID, or access it through the Resource Manager.
There was this one time I wanted to access some Image Resources by name, I mean why not? If I’m aware of the name of the resource why can’t I access it with the file name instead of looking for a resource ID. lol😛 Well actually I had some serious requirement to deal with regarding retrieving the Image Resource by name in one of my projects.
So as usual here I am sharing the code implementation, incase if any of you are going through the same issue, here’s how I implemented it.😉
How to ?
Well it’s the same as retrieving the Resource with the Resource ID, but instead we need to find the Resource ID by the name of the image.
In Xamarin Android we have access to the Resource.Drawable which contains all the Resource ID along with their names, so what we need to do is search through its public field by the specific file name of our Image Resource.
As you can see above first of all we remove the file extension from the filename of the image we want to load and we access the Resource.Drawable public fields to search for the name of the image resource, and finally retrieve the Resource ID.
Now as we have the Resource ID of the image we can retrieve it from our Resources as Bitmap Image.
There you can see I’m using the BitmapFactory to convert the Resource to Bitmap Image, thereby now we can use our Bitmap image as anyways we want.😀 If you need to check whether the ID has been found you could add an IF condition and check whether the ID value is 0 or not
So here’s the full code Implementation…
There you have it folks !😀 Now you may go crazy with it😛 !