[英]Android variables in strings.xml
我在某处阅读了如何在 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 不同,但它曾经有效。 Awww ...感谢您的任何建议。
假设您要将字符串值作为参数传递给another_string
,那么您的字符串格式不正确,无法接收该参数,如果您尝试使用它,您的输出将是{$some_string} trolololo
。
如果您需要使用String.format(String, Object...)格式化您的字符串,那么您可以通过将您的格式参数放入字符串资源中来实现。
<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 = It works! trolololo
another_string = It works! trolololo
.
在此处查看 Android 开发人员官方文档。
这将解决您的问题:
<resources>
<string name="some_string">string1</string>
<string name="another_string">@string/some_string trolololo</string>
</resources>
现在getApplicationContext().getString(R.strings.another_string)
的输出将是string1 trolololo
。
或者,您可以直接使用getResources().getString(R.string.activity_title, arg)
。
例如
<resources>
<string name="postfix_title">%s Gallery</string>
</resources>
然后简单地说,
String arg = "Colors";
String title = getResources().getString(R.string.postfix_title, arg);
这将导致title
包含值Colors Gallery
。
我不确定你做的第一件事是如何使用花括号,但我之前遇到过这个问题,但找不到解决方案。
现在我要做的是分别调用这些字符串并在运行时连接它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.