【问题标题】:Android variables in strings.xmlstrings.xml 中的 Android 变量
【发布时间】:2012-07-16 20:06:52
【问题描述】:

在某处我读到了如何在 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 不同,但它曾经可以工作。哇...感谢您的建议。

【问题讨论】:

  • 清理项目后尝试,然后再次run
  • 嗯...我想知道,这是否也适用于其他类型,如 int 或 int[]

标签: android xml parsing variables


【解决方案1】:

假设您想在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

查看 Android 开发者官方文档,here

【讨论】:

  • 感谢您的回复。我已经看到了这种格式化字符串的方法(之前我在您发布的 Android 开发文档链接上寻找解决方案)。并且 - 是的 - 这将解决我的问题,但我想将所有这些字符串放入 strings.xml 文件中,在那里准备(连接)它们,并在运行时预先准备好的字符串中使用它们。我无法理解的一件事是为什么它可以工作,而现在却不行?
【解决方案2】:

这将解决您的问题:

<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

【讨论】:

  • 有趣的是,当我尝试这个时,我得到了一个错误,No resource found that matches at the given name (at 'another_string' with value '@string/some_string trolololo').
  • DevGuide 表示在 XML 资源引用 '@string/string_name'
  • 是的,是 XML 文件引发了错误。在评论被锁定之前,我没有及时将其编辑到评论中。
  • @BogdanKobylinsky 那只在资源本身以外的XML文件中可用(比如视图)
  • 不幸的是,这种带有@string/some_string 的方法没有。我以这种方式看到了字符串的用法,但是在清单文件中,但是看起来像这样:
【解决方案3】:

或者,您可以直接使用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

【讨论】:

    【解决方案4】:

    我不确定你做的第一件事是如何使用大括号,但我之前遇到过这个问题并且找不到解决方案..

    现在我要做的是分别调用这些字符串并在运行时将它们连接起来。

    【讨论】:

    • 使用大括号我可以引用这个本地文档中的一些字符串值,显然这让我可以连接它们。
    猜你喜欢
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多