173

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

例如:

R.drawable.icon

我需要获取它的整数 ID,但我还需要访问字符串“icon”。

如果我必须传递给该方法的只是“图标”字符串,那将是可取的。

4

14 回答 14

189

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

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

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资源整数值的值

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

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

于 2010-12-13T11:21:40.553 回答
93

您可以使用此函数获取资源 ID。

public static int getResourceId(String pVariableName, String pResourcename, String pPackageName) 
{
    try {
        return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

因此,如果您想获得这样的可绘制调用功能

getResourceId("myIcon", "drawable", getPackageName());

对于字符串,您可以这样称呼它

getResourceId("myAppName", "string", getPackageName());

读这个

于 2013-09-30T11:48:06.897 回答
40

这是基于@Macarse 的答案。

使用它以更快速和代码友好的方式获取资源 ID。

public static int getId(String resourceName, Class<?> c) {
    try {
        Field idField = c.getDeclaredField(resourceName);
        return idField.getInt(idField);
    } catch (Exception e) {
        throw new RuntimeException("No resource ID found for: "
                + resourceName + " / " + c, e);
    }
}

例子:

getId("icon", R.drawable.class);
于 2013-07-12T19:12:52.330 回答
30

如何从资源名称中获取应用程序资源 ID 是一个非常常见且得到很好回答的问题。

如何从资源名称中获取原生 Android资源 id 的回答不太好。这是我通过资源名称获取 Android 可绘制资源的解决方案:

public static Drawable getAndroidDrawable(String pDrawableName){
    int resourceId=Resources.getSystem().getIdentifier(pDrawableName, "drawable", "android");
    if(resourceId==0){
        return null;
    } else {
        return Resources.getSystem().getDrawable(resourceId);
    }
}

可以修改该方法以访问其他类型的资源。

于 2012-04-12T03:10:18.700 回答
12

如果您需要将字符串和 int 配对,那么 Map 呢?

static Map<String, Integer> icons = new HashMap<String, Integer>();

static {
    icons.add("icon1", R.drawable.icon);
    icons.add("icon2", R.drawable.othericon);
    icons.add("someicon", R.drawable.whatever);
}
于 2011-05-14T21:08:16.933 回答
10

我确实喜欢这个,它对我有用:

    imageView.setImageResource(context.getResources().
         getIdentifier("drawable/apple", null, context.getPackageName()));
于 2013-07-26T13:49:08.400 回答
10
Simple method to get resource ID:

public int getDrawableName(Context ctx,String str){
    return ctx.getResources().getIdentifier(str,"drawable",ctx.getPackageName());
}
于 2017-10-09T11:42:25.720 回答
9

您可以使用Resources.getIdentifier(),尽管您需要使用在 XML 文件中使用字符串的格式,即package:drawable/icon.

于 2010-12-13T09:58:45.467 回答
7

既然您说您只想传递一个参数并且似乎无关紧要,您可以传递资源标识符,然后找出它的字符串名称,因此:

String name = getResources().getResourceEntryName(id);

这可能是获得这两个值的最有效方式。您不必四处寻找从较长字符串中的“图标”部分。

于 2014-08-02T07:32:48.507 回答
6

从字符串中获取资源 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);
于 2015-04-27T17:48:33.117 回答
5

Kotlin 方法

inline fun <reified T: Class<*>> T.getId(resourceName: String): Int {
            return try {
                val idField = getDeclaredField (resourceName)
                idField.getInt(idField)
            } catch (e:Exception) {
                e.printStackTrace()
                -1
            }
        }

用法:

val resId = R.drawable::class.java.getId("icon")

或者:

val resId = R.id::class.java.getId("viewId")
于 2019-04-02T02:08:55.220 回答
2

在你的 res/layout/my_image_layout.xml

<LinearLayout ...>
    <ImageView
        android:id="@+id/row_0_col_7"
      ...>
    </ImageView>
</LinearLayout>

要通过其 @+id 值获取该 ImageView,请在您的 java 代码中执行以下操作:

String row = "0";
String column= "7";
String tileID = "row_" + (row) + "_col_" + (column);
ImageView image = (ImageView) activity.findViewById(activity.getResources()
                .getIdentifier(tileID, "id", activity.getPackageName()));

/*Bottom code changes that ImageView to a different image. "blank" (R.mipmap.blank) is the name of an image I have in my drawable folder. */
image.setImageResource(R.mipmap.blank);  
于 2018-04-03T05:25:31.437 回答
1

在 MonoDroid / Xamarin.Android 中,您可以执行以下操作:

 var resourceId = Resources.GetIdentifier("icon", "drawable", PackageName);

但由于 GetIdentifier 在 Android 中不推荐使用 - 您可以像这样使用反射:

 var resourceId = (int)typeof(Resource.Drawable).GetField("icon").GetValue(null);

我建议在其中放置一个 try/catch 或验证您传递的字符串。

于 2016-05-27T17:03:20.203 回答
1

为了从 String 资源名称获取 Drawable id,我正在使用以下代码:

private int getResId(String resName) {
    int defId = -1;
    try {
        Field f = R.drawable.class.getDeclaredField(resName);
        Field def = R.drawable.class.getDeclaredField("transparent_flag");
        defId = def.getInt(null);
        return f.getInt(null);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        return defId;
    }
}
于 2016-06-29T10:41:50.473 回答