Android有没有办法在运行时任意加载资源?
我的 Android 应用程序中有一些 XML 资源。每个都有不同的名称,例如“bicycle.xml”和“car.xml”。我想知道是否有一种方法可以在运行时根据条件加载资源。
举个例子... 假设我的应用程序中有一个文本输入。当用户输入“bicycle”时,我的应用程序可以按该名称查找 XML 资源,解析并加载它。然而,如果他们输入“car”,他们最终会得到另一个 XML 文件中的数据。
到目前为止,我注意到要加载资源,您必须使用自动生成的“R”类,这限制您在编译时对资源进行硬编码。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
Resources#getIdentifier()
在运行时根据资源的名称和类型查找资源的 ID。这使用了针对 R 类的反射,因此相对昂贵。要么不要做太多,要么缓存结果。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.