I need to pass a resource ID to a method in one of my classes. It needs to use both the id that the reference points to and also it needs the string. How should I best achieve this?
For example:
R.drawable.icon
I need to get the integer ID of this, but I also need access to the string "icon".
It would be preferable if all I had to pass to the method is the "icon" string.
You can use this function to get resource ID.
So if you want to get for drawable call function like this
and for string you can call it like this
Read this
How to get an application resource id from the resource name is quite a common and well answered question.
How to get a native Android resource id from the resource name is less well answered. Here's my solution to get an Android drawable resource by resource name:
The method can be modified to access other types of resources.
@EboMike: I didn't know that
Resources.getIdentifier()
existed.In my projects I used the following code to do that:
It would be used like this for getting the value of
R.drawable.icon
resource integer valueI just found a blog post saying that
Resources.getIdentifier()
is slower than using reflection like I did. Check it out.You can use
Resources.getIdentifier()
, although you need to use the format for your string as you use it in your XML files, i.e.package:drawable/icon
.For getting Drawable id from String resource name I am using this code: