java—如何获得具有已知资源名称的资源id?

plupiseo  于 2021-06-27  发布在  Java
关注(0)|答案(10)|浏览(341)

我想通过名称而不是int id来访问像字符串或可绘制的资源。
我该用哪种方法?

ccgok5k5

ccgok5k51#

我发现这个类非常有助于处理资源。它有一些定义的方法来处理尺寸、颜色、可画线和字符串,例如:

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

7tofc5zh2#

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

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

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

ozxc1zmp

ozxc1zmp3#

它将是这样的: R.drawable.resourcename 确保你没有 Android.R 命名空间导入,因为它可能会混淆eclipse(如果您使用的是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)

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

72qzrwbm

72qzrwbm4#

从字符串获取资源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);
wh6knrhe

wh6knrhe5#

我建议您使用我的方法来获取资源id。这比使用getIdentider()方法效率要高得多,因为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;

}
odopli94

odopli946#

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

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)

hl0ma9xz

hl0ma9xz7#

// 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());
qyuhtwio

qyuhtwio8#

•通过扩展功能的kotlin版本

要在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()
}

•使用

现在,所有资源ID都可以访问,只要您使用 resIdByName 方法:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.
7ajki6be

7ajki6be9#

除了@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());
    }
}
8yoxcaq7

8yoxcaq710#

int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());

相关问题