我在某处读到如何在 XML 文档中使用变量。他们说这很简单,我想是的。我在 Android strings.xml 文件中成功地使用了它。我一整天都这样使用它,直到 android 突然停止解析它并停止将其视为变量。
我是这样使用的:
<resources>
<string name="some_string">string1</string>
<string name="another_string"> {$some_string} trolololo </string>
</resources>
在 java 中通过:getApplicationContext().getString(R.strings.another_string);
getApplicationContext().getString(R.strings.another_string);
在输出中我曾经接收过这样的字符串:
string1 trolololo
现在我只收到:
{$some_string} trolololo
有人知道哪里出了问题吗?我知道 Android 的 XML 可能与标准 XML 不同,但它曾经有效。啊……谢谢你的建议。
最佳答案
假设你想在 another_string
中传递一个字符串值作为参数,那么你的字符串格式不正确,无法接收该参数,如果你尝试使用它,你的输出将是 {$some_string} trolololo
.
If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource.
<resources>
<string name="some_string">string1</string>
<string name="another_string">%1$s trolololo</string>
</resources>
现在您可以使用应用程序中的参数格式化字符串,如下所示:
String arg = "It works!";
String testString = String.format(getResources().getString(R.string.another_string), arg);
Log.i("ARG", "another_string = " + testString);
这样做输出字符串将是 another_string = 它有效! trolololo
.
查看 Android 开发者官方文档,here .
关于strings.xml 中的 Android 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11511760/