如何将String转换为其资源ID(Android Studio) [英] How to convert String to its resource 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屋!