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">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?
android-navigation/app/src/main/res/values/strings. xml.
Let's start with the first part, @string . This is just a way of telling Android to look up a text value from a string resource file. In our case, Android Studio created a string resource file for us called strings. xml, located in the app/src/main/res/values folder.
android:text="@string/hello" /> String string = getString (R. string. hello); You can use either getString(int) or getText(int) to retrieve a string.
String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With