Reputation: 101
Hie sorry, noob here so dont really know termology. What i want to do is replace the end of a command like this
((TextView) findViewById(R.id.rr)).setText(R.string.Constitution);
to something more dynamic, substituting the word Constitution, which is a reference to a string in the strings.xml resource, with a variable. This is the way i thought would work, but it isant
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String textFromSpinner = spinner.getSelectedItem().toString();
if (textFromSpinner.contains(" ")){
textFromSpinner = textFromSpinner.replaceAll(" ", "_");
}
String valueToGet = "R.string" + textFromSpinner;
((TextView) findViewById(R.id.rr)).setText(valueToGet);
}
that refused, I also tried a number of variations that were rejected immediately by Android Studio which showed me red lines.
Please help, and also, please be kind in as i am still learning how to code so i am not knowlegebale
Upvotes: 0
Views: 84
Reputation: 101
int searchId = getResources().getIdentifier(textFromSpinner, "string", this.getPackageName());
if (searchId != 0){
((TextView) findViewById(R.id.rr)).setText(searchId);
} else {
((TextView) findViewById(R.id.rr)).setText(R.string.Please_Select_Option);
}
Upvotes: 0
Reputation: 7344
int stringId = context.getResources().getIdentifier(textFromSpinner, "string", context.getPackageName());
With this line you can get the id of your desired string resource. Then you can pass it to your TextView
:
((TextView) findViewById(R.id.rr)).setText(stringId);
Upvotes: 2
Reputation: 6967
<string name="hello_world">Hello %1$s</string>
Replace @runtime
String str = "World";
str = String.format(getResources().getString(R.string.hello_world), str );
Upvotes: 0
Reputation: 1673
You can call getResource().getIdentifier()
method to retrieve a resource by its name at runtime. Check this: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29
Upvotes: 2