[英]Is it possible to replace the name at the end of the R.string. call with a variable
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. 替换为更具动态性的内容,用构成一词代替“构成”一词,该词是对strings.xml资源中的字符串的引用。 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. 拒绝之后,我还尝试了许多变体,但这些变体立即被Android Studio拒绝,但显示出红线。
Please help, and also, please be kind in as i am still learning how to code so i am not knowlegebale 请帮助,而且,请保持友善,因为我仍在学习如何编码,所以我不知道legebale
You can call getResource().getIdentifier()
method to retrieve a resource by its name at runtime. 您可以在运行时调用
getResource().getIdentifier()
方法以按资源名称检索资源。 Check this: 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
int stringId = context.getResources().getIdentifier(textFromSpinner, "string", context.getPackageName());
With this line you can get the id of your desired string resource. 通过此行,您可以获取所需字符串资源的ID。 Then you can pass it to your
TextView
: 然后,您可以将其传递给
TextView
:
((TextView) findViewById(R.id.rr)).setText(stringId);
<string name="hello_world">Hello %1$s</string>
Replace @runtime 替换@runtime
String str = "World";
str = String.format(getResources().getString(R.string.hello_world), str );
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.