我正在使用android studio,并尝试通过其变量名称输出特定的字符串。本质上,我有一个测验,根据用户的回答,测验的结果会有所不同。
在我的Java代码中,
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中的resources.strings文件中定义。
没有中间部分,代码可以正常工作,但是当我尝试通过变量调用字符串名称时,它不起作用。
输入一个特定的字符串名称,就可以了。
有什么方法可以将变量放在那里,而无需一些巨大的if / else嵌套语句?
答案 0 :(得分:0)
如果我理解正确,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