strings.xml中的Android变量

bpa*_*ski 8 xml variables parsing android

在某处我读了如何在XML文档中使用变量.他们说这很简单,我想是的.我在Android strings.xml文件中成功地使用了它.我一整天都在使用它,直到突然android停止解析它并停止将其视为变量.

我用这种方式使用它:

<resources>
<string name="some_string">string1</string>
<string name="another_string"> {$some_string} trolololo </string>
</resources>
Run Code Online (Sandbox Code Playgroud)

并通过java访问它:getApplicationContext().getString(R.strings.another_string);

getApplicationContext().getString(R.strings.another_string);
Run Code Online (Sandbox Code Playgroud)

在我用来接收字符串的输出中:

string1 trolololo
Run Code Online (Sandbox Code Playgroud)

现在我只收到:

{$some_string} trolololo
Run Code Online (Sandbox Code Playgroud)

有谁知道什么是错的?我知道Android的XML可能与标准XML不同,但是它可以用于工作.Awww ...感谢任何建议.

yug*_*oid 18

假设您想要将字符串值作为参数传递,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>
Run Code Online (Sandbox Code Playgroud)

现在您可以使用应用程序中的参数格式化字符串,如下所示:

String arg = "It works!";
String testString = String.format(getResources().getString(R.string.another_string), arg);
Log.i("ARG", "another_string = " + testString);
Run Code Online (Sandbox Code Playgroud)

这样输出字符串就是another_string = It works! trolololo.

这里查看Android开发者官方文档.


Bog*_*kyi 7

这将解决您的问题:

<resources>
    <string name="some_string">string1</string>
    <string name="another_string">@string/some_string trolololo</string>
</resources>
Run Code Online (Sandbox Code Playgroud)

现在输出getApplicationContext().getString(R.strings.another_string)将是string1 trolololo.