如何获取具有已知资源名称的资源 ID? [英] How to get a resource id with a known resource name?
问题描述
我想通过名称而不是 int id 访问像 String 或 Drawable 这样的资源.
我会使用哪种方法?
它将类似于:
R.drawable.resourcename
确保您没有导入 Android.R
命名空间,因为它可能会混淆 Eclipse(如果您正在使用该命名空间).
如果这不起作用,您始终可以使用上下文的 getResources
方法...
Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
其中 this.context
被初始化为 Activity
、Service
或任何其他 Context
子类.>
更新:
如果是你想要的名字,Resources
类(由 getResources()
返回)有一个 getResourceName(int)
方法,并且getResourceTypeName(int)
?
更新 2:
Resources
类有这个方法:
public int getIdentifier (String name, String defType, String defPackage)
返回指定资源名称的整数,类型 &包.
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?
It will be something like:
R.drawable.resourcename
Make sure you don't have the Android.R
namespace imported as it can confuse Eclipse (if that's what you're using).
If that doesn't work, you can always use a context's getResources
method ...
Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
Where this.context
is intialised as an Activity
, Service
or any other Context
subclass.
Update:
If it's the name you want, the Resources
class (returned by getResources()
) has a getResourceName(int)
method, and a getResourceTypeName(int)
?
Update 2:
The Resources
class has this method:
public int getIdentifier (String name, String defType, String defPackage)
Which returns the integer of the specified resource name, type & package.
这篇关于如何获取具有已知资源名称的资源 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!