Android Kotlin StringRes quantityString

好,所以这个:

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) 

问题是你传递format参数作为单个参数,而不是传播到Object... 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) } 

Java中的术语如下所示:

 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) } 
Interesting Posts