Last active
May 2, 2022 18:34
-
-
Save dannyroa/9e8ee539b6414f1accf55ca4b0cc38c0 to your computer and use it in GitHub Desktop.
TextResource
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.res.Resources | |
import androidx.annotation.PluralsRes | |
import androidx.annotation.StringRes | |
// from https://hannesdorfmann.com/abstraction-text-resource/ | |
sealed class TextResource { | |
companion object { | |
// Just needed for static method factory so that we can keep concrete implementations file private | |
fun fromText(text: String): TextResource = SimpleTextResource(text) | |
fun fromStringId(@StringRes id: Int, vararg formatArgs: Any): TextResource = | |
IdTextResource(id, formatArgs.toList()) | |
fun fromPlural(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): TextResource = | |
PluralTextResource(id, quantity, formatArgs.toList()) | |
} | |
} | |
private data class SimpleTextResource( | |
val text: String | |
) : TextResource() | |
private data class IdTextResource( | |
@StringRes val id: Int, | |
val formatArgs: List<Any?>?, | |
) : TextResource() | |
private data class PluralTextResource( | |
@PluralsRes val pluralId: Int, | |
val quantity: Int, | |
val formatArgs: List<Any> | |
) : TextResource() | |
@Suppress("SpreadOperator") | |
fun TextResource.asString(resources: Resources): String = when (this) { | |
is SimpleTextResource -> this.text | |
is IdTextResource -> { | |
if (formatArgs == null) { | |
resources.getString(this.id) | |
} else { | |
resources.getString(this.id, *formatArgs.map { it }.toTypedArray()) | |
} | |
} | |
is PluralTextResource -> resources.getQuantityString( | |
this.pluralId, | |
this.quantity, | |
*formatArgs.toTypedArray() | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment