0

我的strings.xml中有 3 个字符串。

<string name="string1">Hello from string1</string>
<string name="string2">Hello from string2</string>
<string name="string3">Hello from string3</string>

现在,我有一个方法可以传递像“ string1 ”或“ string2 ”这样的字符串:

void showStringToast(String sName) {
    Toast.makeText(this, getString(R.string.[sName]), Toast.LENGTH_LONG).show();
}

当 sName 作为参数传递时,如何正确引用 R.string.sName?

4

5 回答 5

2
// try this
void showStringToast(String sName) {
        Toast.makeText(this, getString(getResources().getIdentifier(sName, "string", getPackageName())), Toast.LENGTH_LONG).show();
    }
于 2013-10-15T04:27:00.357 回答
2

您可以使用以下方式将参数传递给您的字符串:

<string name="string1">Hello from %1$s (or $d if you want to pass integer) %2$d (second parameter)</string>

现在从 getstring 方法传递参数:

getString(R.string.string1,first parameter ,second parameter ...);在此处输入图像描述

看到这个

于 2013-10-15T04:18:57.213 回答
1

我没有尝试过这段代码,但我相信你可以改用 HashMaps。

在某处声明一个静态 HashMap,比如在 Constants.java 中

public static HashMap<String, String> map = new HashMap<String, String>();

然后初始化你的地图。这必须在方法或构造函数中

map.put("string1", "Hello from string1");
map.put("string2", "Hello from string2");
map.put("string3", "Hello from string3");

现在您可以通过以下方式找到您的字符串:

Toast.makeText(this, Constants.map.get(sName).toString(), Toast.LENGTH_LONG).show();

不要忘记导入 Constants.java

于 2013-10-15T04:17:47.460 回答
0

R.string.something is an integer value that contains a reference to your string. So , R.string.something is like a variable here. Have you ever done such thing that you have generated a variable by appending some string to make it like a variable name and your generated variable name working like a variable ? :)

Instead you can do like this. In your java source file , take your required string values to a String array from your resources. Then use them when necessary. Hope it helps.

于 2013-10-15T03:58:06.867 回答
0

试试这种方式:

  void showStringToast(int sName) {
Toast.makeText(this, getString(sName), Toast.LENGTH_LONG).show();
 } 
于 2013-10-15T04:15:40.980 回答