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

查看:311
本文介绍了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,但我也需要访问字符串图标。

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

这将是preferable如果所有我不得不传递给方法是图标字符串。

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.

在我的项目中我用下面的code做到这一点:

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

这将是像这样使用:

It would be used like this:

getResId("icon", context, Drawable.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天全站免登陆