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

查看:32
本文介绍了如何将字符串转换为其资源 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,

我的建议是,

使用您的字符串资源名称,例如resource_150

use your String resource name something like, resource_150

150

现在这里 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.

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

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