好的,所以这是:
fun Context.quantityFromRes(id_: Int, qtt:Int, vararg format: Any) = resources.getQuantityString(id_, qtt, format)
xml:
<plurals name="header_view">
<item quantity="one">Oh no! You just lost %1$d Point</item>
<item quantity="other">Oh no! You just lost %1$d Points</item>
</plurals>
产生了以下错误:
"java.util.IllegalFormatConversionException: %d can't format [Ljava.lang.Object; arguments"
显然的Java修复方法:
public class XmlPluralFormatter {
private XmlPluralFormatter() {
throw new IllegalStateException("You can't fuck me =(");
}
public static String getFormattedString(Context context, int stringRes, int qtt, Object... formatArgs){
return context.getResources().getQuantityString(stringRes,qtt, formatArgs);
}
public static String getFormattedString(Context context, int stringRes, int qtt){
return context.getResources().getQuantityString(stringRes,qtt);
}
}
- 我刚意识到使用Java可以解决这个问题,但我不知道有没有Kotlin的方法可以达到同样的效果。
PS:忘记调用:
val qtt: Int = 123
context.quantityFromRes(R.plurals.header, qty)
我也可以这样做:
fun Context.quantityFromRes(id_: Int, qtt:Int, vararg format: Object) = resources.getQuantityString(id_, qtt, format)
但是,接着来看。
Required Object, found Int
我也可以投射:
context.quantityFromRes(R.plurals.header, qty, qt as Object)
但也提供:
"java.util.IllegalFormatConversionException: %d can't format [Ljava.lang.Object; arguments"
此外,直接使用代码而不是扩展函数也可以起作用:
context.resources.getQuantityString(R.plurals.header, qtt, qtt)