在Android中使用动态R字符串 [英] Use dynamic R strings in Android

查看:509
本文介绍了在Android中使用动态R字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用strings.xml中存储的字符串时遇到问题,我在其中存储了大量的字符串.它们对我非常有用,因为我正在使用它们来翻译程序.但是,现在我想在这些字符串之间动态选择,而且我不知道该怎么做.通过示例将更容易理解.假设我有以下字符串:

I'm having a problem using strings stored in my strings.xml, I have a wide list of strings stored there. They are very useful for me because I'm using them to translate my program. However, now I want to choose between those strings dynamically and I don't know how to do it. It will be easier to understand with an example. Let's assume that I have the following strings:

<string name="red">Red</string>
<string name="blue">Blue</string>
<string name="green">Green</string>
<string name="yellow">Yellow</string>

现在让我们假设我有一个函数,该函数向我传递带有颜色的字符串,例如"yellow".现在,我只有一个解决方案,可以进行非常大的切换(非常大,因为我有很多字符串),我认为必须有一个选项可以将函数的输出转换为正确的参数. 我的意思是,如果我有一个返回"yellow"的函数,并且我想使用R.strings.yellow,则它们之间必须存在链接.我不知道您是否可以使用任何一种反射方式来实现这一目标.

And now let's assume that I have a function that passes me a string with a color, for example "yellow". Now I only have a solution for this, to make a very huge switch (very very huge, because I have lots of strings), I think that there must be an option to transform the output of my function into the right parameter. I mean, if I have a function that returns me "yellow", and I want to use R.strings.yellow, there must be a link between them. I don't know if maybe you could use any kind of reflection to achieve this.

你能帮我吗?

推荐答案

使用两步过程查找要加载的ID.首先使用Resources.getIdentifier(),例如:

Use a two-step process to find the id to load. First use Resources.getIdentifier(), for example:

int id = getResources().getIdentifier("yellow", "string", getPackageName());

然后,在检查id不为零(表明它找不到资源)之后,使用id获取类似于正常的字符串:

Then, after checking the id is not zero (which indicates it could not find the resource), use the id to get a string like normal:

String colour = getString(id);

这篇关于在Android中使用动态R字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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