我想访问一个资源,如字符串或Drawable通过它的名字,而不是它的int id。

我该用哪种方法呢?


当前回答

它会是这样的:

R.drawable.resourcename

确保你没有安卓系统。导入R名称空间,因为它会混淆Eclipse(如果您正在使用Eclipse的话)。

如果这不起作用,你总是可以使用上下文的getResources方法…

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

这个地方。context被初始化为一个Activity, Service或任何其他context子类。

更新:

如果它是你想要的名称,资源类(由getResources()返回)有一个getResourceName(int)方法,和一个getResourceTypeName(int)?

更新2:

Resources类有这样的方法:

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

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

其他回答

•Kotlin版本通过扩展功能

在Kotlin中通过名称查找资源id,在Kotlin文件中添加以下代码片段:

ExtensionFunctions.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")
.
.
.    

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

如果我没理解错的话,这就是你想要的

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

这里的“this”是一个活动,写出来只是为了澄清。

如果你想要strings.xml中的String或者UI元素的标识符,请替换为"drawable"

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

我警告您,这种获取标识符的方法非常缓慢,仅在需要时使用。

官方文档链接:参考资料。getIdentifier(字符串名称,字符串defType,字符串defPackage)

如果你需要在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.
   }

//然后使用drawableId

like painterResource(id = drawableId)

它会是这样的:

R.drawable.resourcename

确保你没有安卓系统。导入R名称空间,因为它会混淆Eclipse(如果您正在使用Eclipse的话)。

如果这不起作用,你总是可以使用上下文的getResources方法…

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

这个地方。context被初始化为一个Activity, Service或任何其他context子类。

更新:

如果它是你想要的名称,资源类(由getResources()返回)有一个getResourceName(int)方法,和一个getResourceTypeName(int)?

更新2:

Resources类有这样的方法:

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

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