Java Android,从字符串中获取资源ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4427608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:20:23  来源:igfitidea点击:

Android, getting resource ID from string?

javaandroidresourcesandroid-resources

提问by Hamid

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?

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

For example:

例如:

R.drawable.icon

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

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

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

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

采纳答案by Macarse

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

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

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 for getting the value of R.drawable.iconresource integer value

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

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

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

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

回答by EboMike

You can use Resources.getIdentifier(), although you need to use the format for your string as you use it in your XML files, i.e. package:drawable/icon.

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

回答by Peter Knego

If you need to pair a string and an int, then how about a Map?

如果您需要配对一个字符串和一个 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);
}

回答by Martin Pearman

How to get an applicationresource id from the resource name is quite a common and well answered question.

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

How to get a native Androidresource id from the resource name is less well answered. Here's my solution to get an Android drawable resource by resource name:

如何从资源名称中获取原生 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);
    }
}

The method can be modified to access other types of resources.

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

回答by Daniel De León

This is based on @Macarse answer.

这是基于@Macarse 的回答。

Use this to get the resources Id in a more faster and code friendly way.

使用它以更快和代码友好的方式获取资源 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);
    }
}

Example:

例子:

getId("icon", R.drawable.class);

回答by Sarvar Nishonboev

I did like this, it is working for me:

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

    imageView.setImageResource(context.getResources().
         getIdentifier("drawable/apple", null, context.getPackageName()));

回答by Azhar

You can use this function to get resource ID.

您可以使用此函数获取资源 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;
    } 
}

So if you want to get for drawablecall function like this

所以如果你想获得像这样的可绘制调用函数

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

and for string you can call it like this

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

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

Read this

读这个

回答by Steve Waring

Since you said you only wanted to pass one parameter and it did not seem to matter which, you could pass the resource identifier in and then find out the string name for it, thus:

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

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

This might be the most efficient way of obtaining both values. You don't have to mess around finding just the "icon" part from a longer string.

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

回答by Muhammad Adil

A simple way to getting resource ID from string. Here resourceNameis the name of resource ImageView in drawable folder which is included in XML file as well.

从字符串中获取资源 ID 的简单方法。这里的resourceName是 drawable 文件夹中资源 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);

回答by Daniele D.

In MonoDroid / Xamarin.Android you can do:

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

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

But since GetIdentifier it's not recommended in Android - you can use Reflection like this:

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

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

where I suggest to put a try/catch or verify the strings you are passing.

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