字符串资源文件中的format语句(format statement in a string resource file)

编程入门 行业动态 更新时间:2024-10-27 21:12:00
字符串资源文件中的format语句(format statement in a string resource file)

我在常用的strings.xml中定义了字符串资源文件,如下所示:

<string name="hello_world"> HELLO</string>

是否可以定义如下所示的格式字符串

result_str = String.format("Amount: %.2f for %d days ", var1, var2);

在strings.xml资源文件中?

我试图逃避特殊字符,但它不工作。

I have strings defined in the usual strings.xml Resource file like this:

<string name="hello_world"> HELLO</string>

Is it possible to define format strings such as the one below

result_str = String.format("Amount: %.2f for %d days ", var1, var2);

in the strings.xml resource file?

I tried escaping the special characters but its not working.

最满意答案

您应该将formatted="false"添加到字符串资源


这是一个例子

在你的strings.xml :

<string name="all" formatted="false">Amount: %.2f%n for %d days</string>

在你的代码中:

yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));

You do not need to use formatted="false" in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE] (where [POSITION] is the attribute position and [TYPE] is the variable type), rather than the short versions, for example %s or %d.

Quote from Android Docs: String Formatting and Styling:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal integer. You can format the string with arguments from your application like this:

Resources res = getResources(); String text = res.getString(R.string.welcome_messages, username, mailCount);

更多推荐

本文发布于:2023-08-05 17:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1437508.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   语句   文件   资源   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!