如何获得与已知的资源名称的资源ID? [英] How to get a resource id with a known resource name?
问题描述
我要访问的资源就像一个String或可绘制它的名字,而不是它的INT ID。
I want to access a resource like a String or a Drawable by its name and not its int id.
哪种方法,我会用这个?
Which method would I use for this?
推荐答案
这将是这样的:
R.drawable.resourcename
请确保你没有在 Android.R
命名空间的进口,因为它可以混淆的Eclipse(如果多数民众赞成你使用的是什么)。
Make sure you don't have the Android.R
namespace imported as it can confuse Eclipse (if thats what you're using).
如果不工作,你可以随时使用上下文的 getResources
方法...
If that doesn't work, you can always use a context's getResources
method ...
Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
其中, this.context
被intialised为活动
,服务
或任何其它上下文
的子类。
Where this.context
is intialised as an Activity
, Service
or any other Context
subclass.
更新:
如果这是你想要的名称,资源
类(由返回getResources()
)有一个 getResourceName(INT)
方法和 getResourceTypeName(INT)
?
If it's the name you want, the Resources
class (returned by getResources()
) has a getResourceName(int)
method, and a getResourceTypeName(int)
?
更新2
在资源
类有这个方法:
public int getIdentifier (String name, String defType, String defPackage)
它返回指定的资源名称,类型和放大器的整数。包。
Which returns the integer of the specified resource name, type & package.
这篇关于如何获得与已知的资源名称的资源ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!