198

我想通过它的名称而不是它的 int id 来访问像 String 或 Drawable 这样的资源。

我会使用哪种方法?

4

10 回答 10

363

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

int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());

其中“this”是一个活动,只是为了澄清而写的。

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

int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());

我警告你,这种获取标识符的方式真的很慢,只在需要的地方使用。

官方文档链接:Resources.getIdentifier(String name, String defType, String defPackage)

于 2010-08-13T11:46:28.350 回答
158

它会是这样的:

R.drawable.resourcename

确保您没有Android.R导入名称空间,因为它会混淆 Eclipse(如果您正在使用它)。

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

Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);

Wherethis.context被初始化为ActivityService或任何其他Context子类。

更新:

如果它是您想要的名称,则Resources该类(由返回getResources())有一个getResourceName(int)方法,以及一个getResourceTypeName(int)?

更新 2

该类Resources有这个方法:

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

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

于 2010-08-13T11:42:58.303 回答
25
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
于 2012-05-14T09:34:58.120 回答
22

Kotlin Version通过Extension Function

要在 Kotlin 中按名称查找资源 id,请在 kotlin 文件中添加以下代码段:

扩展函数.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

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

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    
于 2018-09-29T13:11:59.587 回答
15

从字符串中获取资源 ID 的简单方法。这里的 resourceName 是可绘制文件夹中资源 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);
于 2015-04-27T17:53:25.727 回答
11
// 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());
于 2019-08-01T08:11:52.840 回答
6

我建议您使用我的方法来获取资源 ID。它比使用缓慢的 getIdentitier() 方法效率更高。

这是代码:

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

}
于 2011-08-29T08:29:48.543 回答
3

在 Kotlin 中,以下对我来说很好:

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

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

于 2020-06-06T09:49:07.570 回答
0

我发现这个类对处理资源很有帮助。它有一些定义的方法来处理尺寸、颜色、可绘制对象和字符串,例如:

public static String getString(Context context, String stringId) {
    int sid = getStringId(context, stringId);
    if (sid > 0) {
        return context.getResources().getString(sid);
    } else {
        return "";
    }
}
于 2016-06-30T15:27:15.713 回答
0

除了@lonkly 解决方案

  1. 查看反射和字段可访问性
  2. 不必要的变量

方法:

/**
 * 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());
    }
}
于 2017-06-27T15:15:39.827 回答