gpt4 book ai didi

kotlin - Android Kotlin StringRes 数量String

转载 作者:IT老高 更新时间:2023-10-28 13:41:16 28 4
gpt4 key购买 nike

好的,这样:

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

你想要做的是使用 spread operator :

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

关于kotlin - Android Kotlin StringRes 数量String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40025639/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com