我在通常的strings.xml资源文件中定义了这样的字符串:
<string name="hello_world"> HELLO</string>
是否有可能定义像下面这样的格式字符串
result_str = String.format("Amount: %.2f for %d days ", var1, var2);
在strings.xml资源文件中吗?
我尝试转义特殊字符,但没有成功。
我在通常的strings.xml资源文件中定义了这样的字符串:
<string name="hello_world"> HELLO</string>
是否有可能定义像下面这样的格式字符串
result_str = String.format("Amount: %.2f for %d days ", var1, var2);
在strings.xml资源文件中吗?
我尝试转义特殊字符,但没有成功。
formatted="false"
,你只需要使用完全限定的字符串格式标记-%[POSITION]$[TYPE]
(其中[POSITION]
是属性位置,[TYPE]
是变量类型),而不是短版本,例如%s
或%d
。<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);
你应该在字符串资源中添加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));
formatted="false"
可能暗示着字符串不会被格式化。在https://dev59.com/J2cs5IYBdhLWcg3wtmWf#20887690上发布了另一个解决方案。 - LocalPCGuyString.format(getString(R.string.all), 3.12, 2)
:getString(R.string.all, 3.12, 2)
。 - patryk.beza25%
,Android 就会崩溃。 - Henrique de Sousa在文件strings.xml
中定义字符串资源如下:
<string name="string_to_format">Amount: %1$f for %2$d days%3$s</string>
在您的代码中(假设它继承自Context),只需执行以下操作:
String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);
(相比于LocalPCGuy或Giovanny Farto M. 的答案,这里不需要使用 String.format 方法。)
引用自Android文档:
If you need to format your strings using
String.format(String, Object...)
, then you can do so by putting your format arguments in the string resource. For example, with the following resource:
<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 number. You can format the string with arguments from your application like this:
Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
对我而言,在 Kotlin 中,它的运行方式如下:
我的 string.xml 文件
<string name="price" formatted="false">Price:U$ %.2f%n</string>
我的class.kt
var formatPrice: CharSequence? = null
var unitPrice = 9990
formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
Log.d("Double_CharSequence", "$formatPrice")
D/Double_CharSequence: 价格:U$ 99,90
为了获得更好的结果,我们可以这样做
<string name="price_to_string">Price:U$ %1$s</string>
var formatPrice: CharSequence? = null
var unitPrice = 199990
val numberFormat = (unitPrice/100.0).toString()
formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))
fun formatValue(value: String) :String{
val mDecimalFormat = DecimalFormat("###,###,##0.00")
val s1 = value.toDouble()
return mDecimalFormat.format(s1)
}
Log.d("Double_CharSequence", "$formatPrice")
D/Double_CharSequence: 价格:U$ 1.999,90