安卓:使用变量名访问string.xml [英] Android: Accessing string.xml using variable name
问题描述
我想显示一条消息,根据提示我在程序的其他部分接收用户。可以有若干提示&安培的;它们被存储在一个枚举
I want to display a message to the user depending upon a prompt I receive from another part of the program. There can be a number of prompts & they are stored in an enum.
这些是我的提示:
Defs.java
public enum Prompt
{
PromptA,
PromptB,
PromptC,
}
我有存储在资源上,这些线路的外向化字符串:
I have the externalized strings stored in resources on these lines:
RES /价值/ strings.xml中
<string name="PromptA">Error in execution</string>
<string name="PromptB">Process completed successfully</string>
<string name="PromptC">Please try again</string>
现在在我的主要活动屏幕的方法是调用其他部分:
Now in my main Activity screen a method is called by some other part:
public void showPrompt(Prompt prompt) {
String message = getString(R.string.<**what-do-I-put-here?**>);
//show a dialog box with message
}
我知道这与一个巨大的if-else块来完成(有吨在实际应用中提示)或switch语句。 这将是十分可怕的。
I know this can be done with a huge if-else block (there are tons of prompts in the actual application) or a switch statement. It will be really ugly.
有没有更好的方式来做到这一点?
Is there a better way to do this?
推荐答案
请参阅 Resources.getIdentifier
:<一href="http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29">http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29 。你可以尝试这样的:
See Resources.getIdentifier
: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29 . You can try something like this:
public void showPrompt(Prompt prompt, String label) {
String message = (String) getResources().getText(getResources().getIdentifier(label, "string", null));
//show a dialog box with message
}
尝试了这一点,看看是什么一样对你。
Try that out and see what that does for you.
编辑:MEH。试试这个吧。
meh. Try this instead.
public void showPrompt(Prompt prompt, String label) {
String message = (String) getResources().getText(getResources().getIdentifier(label, "string", "<application package class>"));
//show a dialog box with message
}
原来,你必须指定你的包标识符(所以如果你的AndroidManifest.xml中有 com.blah.blah.blah 作为包放进了第三个参数。
Turns out you have to specify the your package identifier (so if your AndroidManifest.xml has com.blah.blah.blah as the Package put that in the third parameter.
这篇关于安卓:使用变量名访问string.xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!