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:

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

📊 A side-by-side product comparison between Sentry and Crashlytics

A free guide pointing out the differences between Sentry and Crashlytics, that’s it. See which is best for your mobile crash reporting needs.

See Comparison