Java 如何获取具有已知资源名称的资源 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3476430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a resource id with a known resource name?
提问by Aswan
I want to access a resource like a String or a Drawable by its name and not its int id.
我想通过名称而不是 int id 访问像 String 或 Drawable 这样的资源。
Which method would I use for this?
我会使用哪种方法?
采纳答案by Rabid
It will be something like:
它会是这样的:
R.drawable.resourcename
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).
确保您没有Android.R
导入命名空间,因为它可能会混淆 Eclipse(如果这是您正在使用的)。
If that doesn't work, you can always use a context's getResources
method ...
如果这不起作用,您始终可以使用上下文的getResources
方法......
Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
Where this.context
is intialised as an Activity
, Service
or any other Context
subclass.
Wherethis.context
初始化为Activity
,Service
或任何其他Context
子类。
Update:
更新:
If it's the name you want, the Resources
class (returned by getResources()
) has a getResourceName(int)
method, and a getResourceTypeName(int)
?
如果这是您想要的名称,则Resources
类(由 返回getResources()
)有一个getResourceName(int)
方法,还有一个getResourceTypeName(int)
?
Update 2:
更新2:
The Resources
class has this method:
这个Resources
类有这个方法:
public int getIdentifier (String name, String defType, String defPackage)
Which returns the integer of the specified resource name, type & package.
它返回指定资源名称、类型和包的整数。
回答by Maragues
If I understood right, this is what you want
如果我理解正确,这就是你想要的
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
Where "this" is an Activity, written just to clarify.
其中“this”是一个活动,只是为了澄清而写的。
In case you want a String in strings.xml or an identifier of a UI element, substitute "drawable"
如果您想要 strings.xml 中的字符串或 UI 元素的标识符,请替换“drawable”
int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
I warn you, this way of obtaining identifiers is really slow, use only where needed.
我警告你,这种获取标识符的方式真的很慢,只在需要的地方使用。
Link to official documentation: Resources.getIdentifier(String name, String defType, String defPackage)
官方文档链接:Resources.getIdentifier(String name, String defType, String defPackage)
回答by Lonkly
I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.
我建议您使用我的方法来获取资源 ID。它比使用速度慢的 getIdentidier() 方法更有效。
Here's the code:
这是代码:
/**
* @author Lonkly
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param с - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> с) {
Field field = null;
int resId = 0;
try {
field = с.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
回答by user1393422
int resourceID =
this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
回答by Muhammad Adil
A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.
从字符串中获取资源 ID 的简单方法。这里的 resourceName 是 drawable 文件夹中资源 ImageView 的名称,该文件夹也包含在 XML 文件中。
int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);
回答by Diego Malone
I have found this classvery helpful to handle with resources. It has some defined methods to deal with dimens, colors, drawables and strings, like this one:
我发现这门课对处理资源非常有帮助。它有一些定义的方法来处理维度、颜色、可绘制对象和字符串,如下所示:
public static String getString(Context context, String stringId) {
int sid = getStringId(context, stringId);
if (sid > 0) {
return context.getResources().getString(sid);
} else {
return "";
}
}
回答by ceph3us
in addition to @lonkly solution
除了@lonkly 解决方案
- see reflections and field accessibility
- unnecessary variables
- 查看反射和字段可访问性
- 不必要的变量
method:
方法:
/**
* lookup a resource id by field name in static R.class
*
* @author - ceph3us
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param с - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> с)
throws android.content.res.Resources.NotFoundException {
try {
// lookup field in class
java.lang.reflect.Field field = с.getField(variableName);
// always set access when using reflections
// preventing IllegalAccessException
field.setAccessible(true);
// we can use here also Field.get() and do a cast
// receiver reference is null as it's static field
return field.getInt(null);
} catch (Exception e) {
// rethrow as not found ex
throw new Resources.NotFoundException(e.getMessage());
}
}
回答by aminography
? Kotlin Version
via Extension Function
? Kotlin Version
通过Extension Function
To find a resource id by its name In Kotlin, add below snippet in a kotlin file:
要按名称查找资源 ID 在 Kotlin 中,请在 kotlin 文件中添加以下代码段:
ExtensionFunctions.kt
扩展函数.kt
import android.content.Context
import android.content.res.Resources
fun Context.resIdByName(resIdName: String?, resType: String): Int {
resIdName?.let {
return resources.getIdentifier(it, resType, packageName)
}
throw Resources.NotFoundException()
}
? Usage
? Usage
Now all resource ids are accessible wherever you have a context reference using resIdByName
method:
现在,只要您使用resIdByName
方法有上下文引用,就可以访问所有资源 ID :
val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.
回答by Manthan Patel
// image from res/drawable
int resID = getResources().getIdentifier("my_image",
"drawable", getPackageName());
// view
int resID = getResources().getIdentifier("my_resource",
"id", getPackageName());
// string
int resID = getResources().getIdentifier("my_string",
"string", getPackageName());