I have a custom folder, file and custom XML resource class in my “res” folder.
I create some custom objects, which I call:
<area id="@+id/someId" name="Some Name" />
I can access them statically by R.id.someId.
However, I need to get the resource id at runtime and I need to do that by the “name”. In other words, I display that “Some Name” in the list and I need to get the id of knowing that the user selected “Some Name” from the ListView. (I am NOT looking for the id of the ListItem, I actually want to search my resources and get the id of the area xml object)
For example:
I would like to do something of the following:
int id = getIdFromResourceName("Some Name");
Is this possible?
I have tried using:
int i = this.getResources().getIdentifier("Some Name", "area", this.getPackageName());
…but that did not seem to work. I always get 0.
EDIT
As suggested below by Geobits, is there a way to load all of the resources from a res file and save them in an array/map, such as Map<id,name> so I can search them later?
Thank you for the help!
I am not sure if this is what you need. But here is my solution proposal. This is how I would do it, if your resource was a drawable:
This is using Reflection, so it won’t be the most efficient approach. If you call this method frequently, you might need to cache the result of
at least.