Android,从字符串中获取资源ID? [英] Android, getting resource ID from string?

查看:36
本文介绍了Android,从字符串中获取资源ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将资源 ID 传递给我的一个类中的方法.它需要使用引用指向的 id 以及它需要的字符串.我应该如何最好地实现这一目标?

I need to pass a resource ID to a method in one of my classes. It needs to use both the id that the reference points to and also it needs the string. How should I best achieve this?

例如:

R.drawable.icon

我需要获取它的整数 ID,但我还需要访问字符串icon".

I need to get the integer ID of this, but I also need access to the string "icon".

如果我必须传递给方法的只是图标"字符串,那就更好了.

It would be preferable if all I had to pass to the method is the "icon" string.

推荐答案

@EboMike:我不知道 Resources.getIdentifier() 存在.

@EboMike: I didn't know that Resources.getIdentifier() existed.

在我的项目中,我使用以下代码来做到这一点:

In my projects I used the following code to do that:

public static int getResId(String resName, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(resName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

它会像这样用于获取R.drawable.icon资源整数值的值

It would be used like this for getting the value of R.drawable.icon resource integer value

int resID = getResId("icon", R.drawable.class); // or other resource class

我刚刚发现一篇博客文章说 Resources.getIdentifier() 比像我一样使用反射慢.检查一下.

I just found a blog post saying that Resources.getIdentifier() is slower than using reflection like I did. Check it out.

这篇关于Android,从字符串中获取资源ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆