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

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

问题描述

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

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

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

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

在strings.xml资源文件中的

吗?

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

解决方案

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

Android文档:字符串格式和样式:

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

在此示例中,格式字符串具有两个参数:%1$s是一个 字符串,%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);

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

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