views:

489

answers:

1

I've got some XML resources in my Android app. Each one has a different name like "bicycle.xml" and "car.xml". I'd like to know if there's a way to load resources based on conditions during run time.

As an example... Say I had a text input in my app. When the user enters "bicycle", my app can look up an XML resource by that name, parse and load it. Whereas if they enter "car", they would end up with the data from the other XML file.

I've noticed so far that to load resources, you have to use the autogenerated "R" class, which restricts you to hard-coding resources at compile time.

+1  A: 

I've noticed so far that to load resources, you have to use the autogenerated "R" class, which restricts you to hard-coding resources at compile time.

You can use Resources#getIdentifier() to find the ID of a resource by its name and type at runtime. This uses reflection against the R class, and therefore is relatively expensive. Either don't do it a lot or cache the results.

CommonsWare
I'm definitely caching what I retrieve and the calls would only be done during a "load" phase, not during normal operation.Are there any alternatives you might suggest to effectively load like this at runtime?
Omega
I am afraid I do not understand your question. `getIdentifier()` won't take seconds, but it's not the sort of thing you want to call, say, for each row in a list that might be flinged (flung?) by the user.
CommonsWare