为了账号安全,请及时绑定邮箱和手机立即绑定

使用变量名调用字符串

使用变量名调用字符串

Smart猫小萌 2021-09-12 19:39:55
我正在使用 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 语句?
查看完整描述

1 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

如果我理解正确,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 



查看完整回答
反对 回复 2021-09-12
  • 1 回答
  • 0 关注
  • 187 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信