如何将String转换为其资源ID(Android Studio) [英] How to convert String to its resource ID (Android Studio)

查看:777
本文介绍了如何将String转换为其资源ID(Android Studio)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的values/strings.xml文件中有一个xml字符串

I have an xml string in my values/strings.xml file

    <string name="pokemon_d">150</string>

我的控制器MainActivity.java中有字符串"150".在我的MainActivity中,如何将该String转换为xml文件中pokemon_d字符串的资源ID?这有可能吗?

And I have the String "150" in my controller MainActivity.java. In my MainActivity, how can I convert that String to the resource ID of the pokemon_d String in the xml file? Is this even possible?

推荐答案

您无法按值获取标识符,但可以使标识符名称看起来像一个值,并按字符串名称获取它,

You can not get identifier by value, but you can make your identifier name look like a value and get it by string name,

所以我建议

使用您的String资源名称,例如resource_150

use your String resource name something like, resource_150

<string name="resource_150">150</string>

现在resource_string.xml文件中的字符串条目中很常见,因此 在您的代码中,

Now here resource_ is common for your string entries in string.xml file, so in your code,

String value = "150";
int resourceId = this.getResources().
             getIdentifier("resource_"+value, "string", this.getPackageName());

现在resourceId的值等同于R.string.resource_150

只需确保此处this代表您的应用程序上下文.在您的情况下,MainActivity.this可以使用.

Just make sure here this represent your application context. In your case MainActivity.this will work.

这篇关于如何将String转换为其资源ID(Android Studio)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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