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

我该用哪种方法呢?


当前回答

我发现这个类在处理资源方面非常有用。它有一些定义的方法来处理尺寸,颜色,drawables和字符串,就像这个:

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

其他回答

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

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

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

如果资源放在mipmap文件夹中,你可以使用参数“mipmap”而不是“drawable”。

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

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

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