我需要通过一个资源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.