strings.xml 中的 Android 变量

标签 android xml parsing variables

我在某处读到如何在 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/

相关文章:

c# - 用于分析日志文件的正则表达式(多行)

regex - 如何使用 R 解析 sysmon 文件以提取某些信息?

java - 如何将 EBNF 重复实现为 Java 代码?

java - addView 到 ScrollView 中的线性布局在刷新时被删除

java - 调用超父类(super class)onResume()和onCreae()

android - 如何获取 DialogFragment 附带的对话框? [安卓]

css - XSLT 试图在本地引用默认的 Mozilla 样式

c# - 从 XMLDocument 中的 xml 文件读取节点

C# - 如果发生错误,则继续进行 foreach() 循环

android - 捕获 BottomSheetDialogFragment 的解雇