Android Kotlin StringRes quantityString

14

好的,所以这是:

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个回答

39
问题在于您将format参数作为单个参数传递,而不是将其扩展到Object... args中。 扩展方法如下:

问题在于您将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)
}

1
使用 spread 是一种优雅的解决方案,感谢您指出。 - j2esu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接