Android 如何将getQuantityText与format参数一起使用,以便在字符串中使用quantity?
对于简单字符串,您可以使用Android 如何将getQuantityText与format参数一起使用,以便在字符串中使用quantity?,android,string-formatting,android-resources,Android,String Formatting,Android Resources,对于简单字符串,您可以使用Resources.getQuantityString(int,int,…),它允许您传递占位符值。因此复数资源可以在字符串中使用%d,您可以插入实际数量 我希望在复数中使用字体标记等。所以我在看参考资料。getQuantityText(int,int)。很遗憾,您无法传递占位符值。我们在源代码中看到,在带有占位符的getQuantityString中,它们使用String.format 使用复数字体格式有解决办法吗?首先,让我们看看“正常”情况(不起作用的情况)。你有
Resources.getQuantityString(int,int,…)
,它允许您传递占位符值。因此复数资源可以在字符串中使用%d,您可以插入实际数量
我希望在复数中使用字体标记
等。所以我在看参考资料。getQuantityText(int,int)
。很遗憾,您无法传递占位符值。我们在源代码中看到,在带有占位符的getQuantityString中,它们使用String.format
使用复数字体格式有解决办法吗?首先,让我们看看“正常”情况(不起作用的情况)。你有一些复数资源,比如:
<plurals name="myplural">
<item quantity="one">only 1 <b>item</b></item>
<item quantity="other">%1$d <b>items</b></item>
</plurals>
textView.setText(getResources().getQuantityString(R.plurals.myplural, 2, 2));
正如您所发现的,这只会导致您看到“2项”,而不使用粗体
解决方案是将资源中的
标记转换为使用html实体。例如:
<plurals name="myplural">
<item quantity="one">only 1 <b>item</b></item>
<item quantity="other">%1$d <b>items</b></item>
</plurals>
现在您将成功地看到“2项”。您可以将字符串包装在
和]>中,而不是转义HTML标记:
<plurals name="myplural">
<item quantity="one"><![CDATA[only 1 <b>item</b>]]></item>
<item quantity="other"><![CDATA[%1$d <b>items</b>]]></item>
</plurals>
谢谢我在网上找到的最好的解释是使用toHtml和fromHtml,这样项目字符串就可以是普通的标记。我更喜欢这个想法,因为它只需要一次转换。为了它的价值,这个解决方案是从谷歌自己的开发者文档改编而来的。请参见此处的“使用HTML标记设置样式”
<plurals name="myplural">
<item quantity="one"><![CDATA[only 1 <b>item</b>]]></item>
<item quantity="other"><![CDATA[%1$d <b>items</b>]]></item>
</plurals>
fun Resources.getQuantityText(id: Int, quantity: Int, vararg formatArgs: Any): CharSequence {
val html = getQuantityString(id, quantity, *formatArgs)
return HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_COMPACT)
}