【问题标题】:How to get a resource id with a known resource name?如何获取具有已知资源名称的资源 id?
【发布时间】:2011-03-29 10:23:21
【问题描述】:

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

我会使用哪种方法?

【问题讨论】:

标签: java android android-resources


【解决方案1】:

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

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)

【讨论】:

  • 这在编写测试以确保某些字符串存在等方面非常有用。
  • 我不知道,我在 getIdentifier() 之前和之后添加了一个带有时间戳的日志,它告诉我它在 0 - 1 毫秒内执行!所以它不慢,它超级快!我正在使用它从资源中获取图像,并且效果很好。在 Nexus5x 上测试。
  • @KirillKarmazin:Nexus5X 是一款速度相当快的手机,1ms 这样的通话速度相当慢。请记住,每个 UI 帧只有 16 毫秒。
  • 你好,如果我想从 raw 文件夹中获取 id,那么我需要使用 "int resourceId = this.getResources().getIdentifier("nameOfResource", "raw", this.getPackageName() );??? 请帮忙
【解决方案2】:

会是这样的:

R.drawable.resourcename

确保您没有导入 Android.R 命名空间,因为它会混淆 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) 

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

【讨论】:

  • 感谢您的回复 .R.drawable.resourcename 我现在正在使用我需要通过传递资源名称来获取它的整数值
  • R.drawable.resourcename 是整数。
  • 嗨 Rabid.what 你说的是有什么方法可以通过传递资源来访问 R.drawable .resource 值
  • 我需要通过动态传递资源名称的整数值
  • Thankq 像这样我想要并且我想要获取可绘制资源 id。我将如何处理它
【解决方案3】:
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());

【讨论】:

    【解决方案4】:

    • Kotlin Version 通过Extension Function

    要在 Kotlin 中按名称查找资源 id,请在 kotlin 文件中的 sn-p 下方添加:

    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

    现在,无论您使用resIdByName 方法,无论您有上下文引用,都可以访问所有资源 ID:

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        【解决方案6】:
        // 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());
        

        【讨论】:

        • 它返回的暗模式在亮模式下,反之亦然
        【解决方案7】:

        我建议您使用我的方法来获取资源 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;
        
        }
        

        【讨论】:

        • 它不适用于所有情况。例如,如果您有 content,则 R.string 类将有一个 string_name 字段。而且你的方法在这一点上不起作用。
        • 另外你的方法实际上并不快。因为 Java 类序列化永远不会很快。
        【解决方案8】:

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

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

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

        【讨论】:

          【解决方案9】:

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

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

          【讨论】:

            【解决方案10】:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-10-09
              • 2014-09-01
              • 1970-01-01
              • 2015-01-30
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多