【问题标题】:Call string with a variable name [duplicate]使用变量名调用字符串[重复]
【发布时间】:2018-09-10 23:22:03
【问题描述】:

我正在使用 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 语句的情况下将变量放在那里?

【问题讨论】:

    标签: java android string variables


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-07-19
      • 2012-07-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多