字符串资源文件中的格式语句 [英] format statement in a string resource file

查看:43
本文介绍了字符串资源文件中的格式语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在常用的 strings.xml 资源文件中定义了这样的字符串:

你好</string>

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

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

在strings.xml 资源文件中?

我尝试转义特殊字符,但它不起作用.

解决方案

您不需要在 XML 中使用 formatted="false".您只需要使用完全限定的字符串格式标记 - %[POSITION]$[TYPE](其中 [POSITION] 是属性位置,[TYPE] 是变量类型),而不是简短的版本,例如 %s%d.

引用自 Android 文档:字符串格式和样式:

<块引用>

你好,%1$s!您有 %2$d 条新消息.</string>

在这个例子中,格式字符串有两个参数:%1$s 是一个string 和 %2$d 是一个十进制整数.您可以使用格式化字符串来自您的应用程序的参数如下:

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

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.

解决方案

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);

这篇关于字符串资源文件中的格式语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆