Skip to content

Instantly share code, notes, and snippets.

@sergio-sastre
Last active March 10, 2022 13:19
Show Gist options
  • Save sergio-sastre/371191e5067c73af747f3d0939e0db29 to your computer and use it in GitHub Desktop.
Save sergio-sastre/371191e5067c73af747f3d0939e0db29 to your computer and use it in GitHub Desktop.
Kotlin Extensions similar to context.getText() but accepting arguments like in String.format(). Full explanation in this post: https://sergiosastre.hashnode.dev/styling-dynamic-strings-directly-in-android-xml
import android.content.Context
import android.text.SpannedString
import android.text.TextUtils
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.core.text.HtmlCompat
fun Context.getStyledText(
@StringRes id: Int,
vararg args: Any
): CharSequence =
getStyledCharSequence(
getText(id),
args.toList()
)
fun Context.getStyledQuantityText(
@PluralsRes id: Int,
quantity: Int,
vararg args: Any
): CharSequence =
getStyledCharSequence(
resources.getQuantityText(id, quantity),
args.toList()
)
private fun Context.getStyledCharSequence(
spannedStringFromRes: CharSequence,
args: List<Any>
): CharSequence {
val escapedArgs = args.map {
if (it is String) TextUtils.htmlEncode(it) else it
}.toTypedArray()
val spannedString = SpannedString(spannedStringFromRes)
val htmlString = HtmlCompat.toHtml(
spannedString,
HtmlCompat.TO_HTML_PARAGRAPH_LINES_INDIVIDUAL
)
.substringBeforeLast('>')
.plus(">")
val dynamicStyledString = String.format(htmlString, *escapedArgs)
val result =
HtmlCompat.fromHtml(
dynamicStyledString,
HtmlCompat.FROM_HTML_MODE_COMPACT
)
return result.removeSuffix("\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment