Android Kotlin StringRes quantityString

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);
    }
}

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});
}

你想做的是使用 spread operator:

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