我的Lintcheck提示我的弦乐资源。
此资源以前是,但我将其更改为普通字符串,例如:
<string name="plain_string">%d Pers</string>
我会理解警告,但会出错?我该如何解决?
最佳答案
将字符串转换为类似here的复数形式:
<plurals name="plain_string">
<item quantity="one">%d Pers</item>
<item quantity="other">%d Pers</item>
</plurals>
在您的代码中,您必须替换getContext().getString(R.string.plain_string, pers)
经过getContext().getResources().getQuantityString(R.plurals.plain_string, pers, pers)
或者只是像这样抑制警告:<string name="plain_string" tools:ignore="PluralsCandidate">%d Pers</string>
Kotlin扩展程序可以处理null并自动以格式传递计数字符串:// note: these methods won't work if you have multiple formats in your string
// plural strings without formatted count ("book", "books")
fun Context.getQuantityString(resId: Int, maybeCount: Int?, defaultCount: Int = 0): String? {
val count = maybeCount ?: defaultCount
return resources?.getQuantityString(resId, count, count)
}
// plural strings with formatted count (e.g. "%d book", "%d books")
fun Context.getPluralString(resId: Int, maybeCount: Int?, defaultCount: Int = 0): String? {
return resources?.getQuantityString(resId, maybeCount ?: defaultCount)
}
// usage
context?.getQuantityString(R.plurals.words_count, nullableCount)