[英]How to get a resource id with a known resource name?
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?我会使用哪种方法?
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)
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).确保您没有导入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. this.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.它返回指定资源名称、类型和包的整数。
int resourceID =
this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
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")
.
.
.
A simple way to getting resource ID from string.从字符串中获取资源 ID 的简单方法。 Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.这里的 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);
// 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());
I would suggest you using my method to get a resource ID.我建议您使用我的方法来获取资源 ID。 It's Much more efficient, than using getIdentidier() method, which is slow.它比使用速度慢的 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;
}
In Kotlin following works fine for me:在 Kotlin 中,以下对我来说很好用:
val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())
If resource is place in mipmap folder, you can use parameter "mipmap" instead of "drawable".如果资源位于 mipmap 文件夹中,则可以使用参数“mipmap”而不是“drawable”。
I have found this class very 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 "";
}
}
in addition to @lonkly solution除了@lonkly 解决方案
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());
}
}
If you need to do this in compose, here how you can do it:如果您需要在 compose 中执行此操作,请按以下步骤操作:
val context = LocalContext.current
val drawableId = remember(iconName) {
//this block will re-calculate each time iconName has changed
val resId by derivedStateOf {
context.resources.getIdentifier(
iconName,
"drawable",
context.packageName
)
}
if (resId != 0) resId else R.drawable.some_fallback_icon //it doesn't throw an error instead resId becomes 0, so we need to check if 0 aka couldn't find the drawable.
}
//then use drawableId //然后使用drawableId
like painterResource(id = drawableId)
像painterResource(id = drawableId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.