How to get Android resource ID by name

arpytoth

Toth Arpad

Posted on January 21, 2019

How to get Android resource ID by name

You may want to do this if you want to write a framework that relies on the name of the resources and not the actual ID, in order to remove references to the R class. For example if you use R.layout.activity_todo_list in your class, and you want to move your class in a separate library… you can’t. R is a generated class and is project specific. An easy solution would be to somehow load the R.layout.activity_todo_list value dynamically at runtime. Luckily, you can do this easily like this:

context.resources.getIdentifier("activity_todo_list", "layout", context.packageName)

As you can see we have no reference to the R class so this piece of code is project agnostic but: it’s not safe! If the resource is missing from the project this code won’t give you a compilation error so your application may fail at runtime. In my case, the benefits of moving the common code for all my apps in a single library was more important than the fact that for some resources I lose the compilation errors so I’m happy with the trade-off but I don’t advise using this technique if you don’t have a really good reason for it.

Share this:

💖 💪 🙅 🚩
arpytoth
Toth Arpad

Posted on January 21, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to get Android resource ID by name