Android Kotlin StringRes quantityString

时间:2016-10-13 15:52:17

标签: kotlin illegalstateexception

好的,这个:

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)

1 个答案:

答案 0 :(得分:13)

问题是您将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});
}

您要做的是使用spread operator

fun Context.quantityFromRes(id_: Int, qtt: Int, vararg format: Any): String? {
    return resources.getQuantityString(id_, qtt, *format)
}