如何获取已知资源名称的资源ID?

发布于 2024-09-14 01:56:31 字数 69 浏览 7 评论 0原文

我想通过名称而不是 int id 来访问 String 或 Drawable 等资源。

我会使用哪种方法呢?

I want to access a resource like a String or a Drawable by its name and not its int id.

Which method would I use for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

云柯 2024-09-21 01:56:32

它将类似于:

R.drawable.resourcename

确保您没有导入 Android.R 命名空间,因为它可能会混淆 Eclipse(如果您是这样的话)使用)。

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

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

其中 this.context 被初始化为 Activity,< code>Service 或任何其他 Context 子类。

更新:

如果这是您想要的名称,Resources 类(由 getResources() 返回)有一个 getResourceName(int)< /code> 方法和 getResourceTypeName(int)

更新2

Resources类有这个方法:

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

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

It will be something like:

R.drawable.resourcename

Make sure you don't have the Android.R namespace imported as it can confuse Eclipse (if that's what you're using).

If that doesn't work, you can always use a context's getResources method ...

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

Where this.context is intialised as an Activity, Service or any other Context subclass.

Update:

If it's the name you want, the Resources class (returned by getResources()) has a getResourceName(int) method, and a getResourceTypeName(int)?

Update 2:

The Resources class has this method:

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

Which returns the integer of the specified resource name, type & package.

陌若浮生 2024-09-21 01:56:32

• 通过扩展函数Kotlin 版本

要通过名称查找资源ID 在Kotlin 中,在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()
}

用法

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

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

Kotlin Version via Extension Function

To find a resource id by its name In Kotlin, add below snippet in a kotlin file:

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

Usage

Now all resource ids are accessible wherever you have a context reference using resIdByName method:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    
饮湿 2024-09-21 01:56:32
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
撩动你心 2024-09-21 01:56:32
// 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());
// 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());
七堇年 2024-09-21 01:56:32

我建议您使用我的方法来获取资源 ID。它比使用速度慢的 getIdentidier() 方法要高效得多。

这是代码:

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

}

I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.

Here's the code:

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

}
意犹 2024-09-21 01:56:32

在 Kotlin 中,以下内容对我来说效果很好:

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

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

In Kotlin following works fine for me:

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

If resource is place in mipmap folder, you can use parameter "mipmap" instead of "drawable".

眉黛浅 2024-09-21 01:56:32

如果您需要在撰写中执行此操作,请按以下方法操作:

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.
   }

//then use drawableId

like painterResource(id = drawableId)

If you need to do this in compose, here how you can do it:

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.
   }

//then use drawableId

like painterResource(id = drawableId)

贪恋 2024-09-21 01:56:32

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

in addition to @lonkly solution

  1. see reflections and field accessibility
  2. unnecessary variables

method:

/**
 * 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());
    }
}
悸初 2024-09-21 01:56:32

我发现此类对于处理资源非常有帮助。它有一些定义的方法来处理尺寸、颜色、绘图和字符串,如下所示:

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

I have found this class very helpful to handle with resources. It has some defined methods to deal with dimens, colors, drawables and strings, like this one:

public static String getString(Context context, String stringId) {
    int sid = getStringId(context, stringId);
    if (sid > 0) {
        return context.getResources().getString(sid);
    } else {
        return "";
    }
}
梦幻之岛 2024-09-21 01:56:31

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

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

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

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

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

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

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

If I understood right, this is what you want

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

Where "this" is an Activity, written just to clarify.

In case you want a String in strings.xml or an identifier of a UI element, substitute "drawable"

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

I warn you, this way of obtaining identifiers is really slow, use only where needed.

Link to official documentation: Resources.getIdentifier(String name, String defType, String defPackage)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文