Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lint check potential plurals?

My Lintcheck complains regarding my string resources.

Potential Plurals res/values/strings.xml Formatting %d followed by words ("Pers"): This should probably be a plural rather than a string

This Resource was previously a , but I changed this to a normal string like:

<string name="plain_string">%d Pers</string>

I would understand a warning, but a error? How can I solve this?

like image 468
Ralf Wickum Avatar asked Nov 22 '17 16:11

Ralf Wickum


1 Answers

Convert the string to a plural like descriped here:

<plurals name="plain_string">
    <item quantity="one">%d Pers</item>
    <item quantity="other">%d Pers</item>
</plurals>

In your code you have to replace

getContext().getString(R.string.plain_string, pers)

by

getContext().getResources().getQuantityString(R.plurals.plain_string, pers, pers)

Or just suppress the warning like this:

<string name="plain_string" tools:ignore="PluralsCandidate">%d Pers</string>

Kotlin extension that handles null and automatically passes in count for strings with formatting:

// 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)
like image 134
masewo Avatar answered Feb 16 '23 00:02

masewo