Java 如何获取具有已知资源名称的资源id?

Java 如何获取具有已知资源名称的资源id?,java,android,android-resources,Java,Android,Android Resources,我希望通过名称而不是int-id来访问字符串或可绘制的资源 我将使用哪种方法进行此操作?它将类似于: R.drawable.resourcename 确保没有导入Android.R名称空间,因为如果您使用的是Android.R名称空间,它可能会混淆Eclipse 如果这不起作用,您可以始终使用上下文的getResources方法 Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource); 其中t

我希望通过名称而不是int-id来访问字符串或可绘制的资源


我将使用哪种方法进行此操作?

它将类似于:

R.drawable.resourcename

确保没有导入Android.R名称空间,因为如果您使用的是Android.R名称空间,它可能会混淆Eclipse

如果这不起作用,您可以始终使用上下文的getResources方法

Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
其中this.context被初始化为活动、服务或任何其他context子类

更新:

如果它是您想要的名称,那么getResources返回的Resources类有一个getResourceNameint方法和一个getResourceTypeNameint

更新2:

Resources类具有以下方法:

public int getIdentifier (String name, String defType, String defPackage) 

返回指定资源名称、类型和包的整数。

如果我理解正确,这就是您想要的

int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
如果这是一项活动,写下来只是为了澄清

如果需要strings.xml中的字符串或UI元素的标识符,请替换为drawable

int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
我警告你,这种获取标识符的方法非常慢,只在需要的地方使用


链接到官方文档:

我建议您使用我的方法来获取资源ID。它比使用GetIdentider方法效率更高,后者速度较慢

代码如下:

/**
 * @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;

}

从字符串获取资源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);
我发现处理资源非常有帮助。它有一些已定义的方法来处理尺寸、颜色、可拉伸和字符串,例如:

public static String getString(Context context, String stringId) {
    int sid = getStringId(context, stringId);
    if (sid > 0) {
        return context.getResources().getString(sid);
    } else {
        return "";
    }
}

除了@lonkly解决方案

请参见反射和现场可访问性 不必要的变量 方法:

/**
 * 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());
    }
}
•通过扩展功能实现Kotlin版本 要在Kotlin中按名称查找资源id,请在Kotlin文件中添加以下代码段:

ExtensionFunctions.kt

•使用 现在,使用resIdByName方法,只要有上下文引用,就可以访问所有资源ID:


在科特林,以下工作对我来说很好:

val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())

如果资源位于mipmap文件夹中,您可以使用参数mipmap而不是drawable。

谢谢您的回复。我现在使用的是R.drawable.resourcename,我需要通过传递resourcenameR.drawable.resourcename来获取其整数值。您好,Rabid。您刚才说的是,通过传递resource来访问R.drawable.resource值有什么办法吗像这样传递resourcename DynamicAllyTankQ,我想要并且我想要获得可绘制的资源id。我将如何使用它可能的重复项并不适用于所有情况。例如,如果您有内容,那么R.string类将有一个string\u name字段。你的方法在这一点上是行不通的,而且你的方法实际上也不快。因为Java类序列化永远不会快速工作。这在编写测试以确保某些字符串存在的上下文中非常有用。我不认识man,我在getIdentifier之前和之后添加了一个带有时间戳的日志,它向我显示它在0-1毫秒内执行!所以它不慢,它超快!我用它从资源中获取图像,它工作得非常好。在Nexus5x上测试。@KirillKarmazin:Nexus5x是一款速度相当快的手机,这种通话的1ms速度相当慢。请记住,每个UI帧只有16ms。您好,如果我想从原始文件夹获取id,那么我需要使用int-resourceId=this.getResources.getIdentifiernameOfResource,raw,this.getPackageName;???plz帮助其在亮模式下返回暗模式res,反之亦然
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()
}
val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    
// 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());
val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())