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.
These are my prompts:
Defs.java
public enum Prompt
{
PromptA,
PromptB,
PromptC,
}
I have the externalized strings stored in resources on these lines:
res/values/strings.xml
<string name="PromptA">Error in execution</string>
<string name="PromptB">开发者_C百科;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
}
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?
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.
EDIT: 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
}
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.
What you could do is just enclose the line in a if/else if/else statement, or a switch.
String message;
switch(prompt) {
case PromptA:
message = getString(R.string.PromptA);
break;
case PromptB:
message = getString(R.string.PromptB);
break;
case PromptC:
message = getString(R.string.PromptC);
break;
default:
message = "";
}
I'm not on the machine I usually develop on, so there may be some silly syntax error in there, but the logic 'should' work.
精彩评论