Skip to content

Instantly share code, notes, and snippets.

@maulikhirani
Created January 17, 2024 05:10
Show Gist options
  • Save maulikhirani/4496b4cc9fb23e92ac40071eb20feffe to your computer and use it in GitHub Desktop.
Save maulikhirani/4496b4cc9fb23e92ac40071eb20feffe to your computer and use it in GitHub Desktop.
Highlight the words between curly braces
private fun getTextWithHighlights(text: String): CharSequence {
// Initialize spannable string without any formatting
val spannableString = SpannableStringBuilder(text)
// Regex to find words between curly braces i.e {test}
val regex = Regex("\\{(.*?)\\}")
// List of index for the curly braces which needs to be removed after formatting
val symbolsToRemoveIndices = mutableListOf<Int>()
// iterate over all the words within curly braces
regex.findAll(spannableString).forEach {
// Set the color of the word
spannableString.setSpan(
ForegroundColorSpan(
ContextCompat.getColor(
activity,
R.color.highlightColor
)
),
it.range.first,
it.range.last + 1,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
)
// Set the font of the word
spannableString.setSpan(
CustomTypefaceSpan(
"",
ResourcesCompat.getFont(
activity,
R.font.highlightFont
)),
it.range.first,
it.range.last + 1,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
)
// Save index of curly braces to the list to remove after formatting
symbolsToRemoveIndices.add(it.range.first)
symbolsToRemoveIndices.add(it.range.last)
}
// Remove all curcly braces
symbolsToRemoveIndices.sortedDescending().forEach {
spannableString.replace(
it, it + 1, ""
)
}
return spannableString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment