Accessing Android Resources By Name at Runtime
Use the getIdentifier method passing it the name of your resource, the resource type (id, raw) and your package name ( just use getPackageName())
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
After that you can use the id just like you would at compile time using the R class.
Updated: May 21, 2010 – The code that was here for a long time was awful and dated, so I’ve updated this post.
eisernWolf 6:37 am on March 31, 2009 Permalink |
See Resources.getIdentifier. For example: http://www.anddev.org/viewtopic.php?p=17846
steven 7:03 am on March 31, 2009 Permalink |
Ah, absolutely. This post is _very_ dated and I not recommend using my code example to anyone.
carlos 3:19 am on September 28, 2009 Permalink |
but with the example http://www.anddev.org/viewtopic.php?p=17846, we can’t get a button id for example. Steven, it could be possible with your code example, but is it recommendable? please, help me with this little trouble. (you can send me a mail)
steven 10:01 am on October 3, 2009 Permalink |
This code is really dated, I know there is a much cleaner way to do this now, but unfortunately I haven’t kept up with my Android development and can’t be to much help.
Tim H 4:55 pm on October 16, 2009 Permalink |
Carlos,
You want this:
Log.i(TAG, “Found Button ID: ” + getResources().getIdentifier(“Button01″, “id”, “com.android.test”));
or
Log.i(TAG, “Found Button ID: ” + getResources().getIdentifier(“com.android.test:id/Button01″));
The code mentioned shows how to get a drawable, just replace drawable for another type in the resource file (id, drawable, layout, string, etc)
keckia 7:37 pm on March 1, 2010 Permalink |
thanx, thats what I needed
Janusz Leidgens 8:56 am on June 30, 2010 Permalink |
thanks the documentation sadly lacks an example
Christopher 10:13 am on October 12, 2010 Permalink |
Thank you so much for your help Steve!
You are my hero of the day
Murat 5:38 pm on April 21, 2012 Permalink |
Thank you so much Steve !!! That is great example..
Scott 3:12 am on June 2, 2012 Permalink |
Thanks so much!!!