Is there a way to arbitrarily load Resources at runtime in Android?

不打扰是莪最后的温柔 提交于 2019-12-07 08:17:20

问题


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:


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.



来源:https://stackoverflow.com/questions/2398264/is-there-a-way-to-arbitrarily-load-resources-at-runtime-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!