使用变量名调用字符串

我正在使用 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 语句?


Smart猫小萌
浏览 188回答 1
1回答

慕标5832272

如果我理解正确,R.string.stringVariable显然不会工作,因为它R.string是一个已编译的资源类并且stringVariable需要是一个动态值。您可以改用这些选项int resID = getResources().getIdentifier(stringVariable, "string", getPackageName());textview.setText(resID);  // directly set itString content = getString(resID); // get the variable, then concatenate with other content 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java