DEV Community

Toth Arpad
Toth Arpad

Posted on

1

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:

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay