Android Kotlin StringRes quantityString
好的,那么这个:Android Kotlin StringRes quantityString,kotlin,illegalstateexception,Kotlin,Illegalstateexception,好的,那么这个: fun Context.quantityFromRes(id_: Int, qtt:Int, vararg format: Any) = resources.getQuantityString(id_, qtt, format) xml: 明显的Java修复: public class XmlPluralFormatter { private XmlPluralFormatter() { throw new IllegalStateException(
fun Context.quantityFromRes(id_: Int, qtt:Int, vararg format: Any) = resources.getQuantityString(id_, qtt, format)
xml:
明显的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方法可以实现同样的目标
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)
问题是您正在将
格式
参数作为单个参数传递,而不是将其扩展到对象。。。args
。扩展方法:
fun Context.quantityFromRes(id_: Int, qtt:Int, vararg format: Any) = resources.getQuantityString(id_, qtt, format)
相当于:
fun Context.quantityFromRes(id_: Int, qtt: Int, vararg format: Any): String? {
val args: Array<out Any> = format
return resources.getQuantityString(id_, qtt, args)
}
您要做的是使用:
使用spread是一个优雅的解决方案,感谢您指出这一点
fun Context.quantityFromRes(id_: Int, qtt:Int, vararg format: Any) = resources.getQuantityString(id_, qtt, format)
fun Context.quantityFromRes(id_: Int, qtt: Int, vararg format: Any): String? {
val args: Array<out Any> = format
return resources.getQuantityString(id_, qtt, args)
}
public static final String quantityFromRes(Context $receiver, int id_, int qtt, Object... format) {
return $receiver.getResources().getQuantityString(id_, qtt, new Object[]{format});
}
fun Context.quantityFromRes(id_: Int, qtt: Int, vararg format: Any): String? {
return resources.getQuantityString(id_, qtt, *format)
}