Java 使用变量名调用字符串
我使用的是android studio,我试图通过它的变量名输出一个特定的字符串。基本上,我有一个测验,根据用户的答案,它有不同的结果 在我的java代码中Java 使用变量名调用字符串,java,android,string,variables,Java,Android,String,Variables,我使用的是android studio,我试图通过它的变量名输出一个特定的字符串。基本上,我有一个测验,根据用户的答案,它有不同的结果 在我的java代码中 private void displayFinal(String stringVariable) { TextView quantityTextView = (TextView) findViewById(R.id.choice); String outPut = "some text here \n"; outPu
private void displayFinal(String stringVariable) {
TextView quantityTextView = (TextView) findViewById(R.id.choice);
String outPut = "some text here \n";
outPut += stringVariable+"\n";
outPut += getString(R.string.stringVariable);
outPut += "\n more text here";
quantityTextView.setText(outPut);
}
这里stringVariable是一个字符串,根据测验答案,它在12个值中的1个值之间变化。所有12个都在android studio中的my resources.strings文件中定义
如果没有中间部分,代码可以正常工作,但是当我试图通过变量调用字符串名称时,它不起作用
输入一个特定的字符串名,它就可以正常工作了
有没有办法在不使用一些大型嵌套if/else语句的情况下将变量放在那里?如果我理解正确,
R.string.stringVariable
显然不起作用,因为R.string
是一个编译过的资源类,stringVariable
需要是一个动态值
您可以改为使用这些选项
int resID = getResources().getIdentifier(stringVariable, "string", getPackageName());
textview.setText(resID); // directly set it
String content = getString(resID); // get the variable, then concatenate with other content