Skip to content

Instantly share code, notes, and snippets.

@gideonseven
Last active October 20, 2022 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gideonseven/113fe76726cc39484e7d42218741a69a to your computer and use it in GitHub Desktop.
Save gideonseven/113fe76726cc39484e7d42218741a69a to your computer and use it in GitHub Desktop.
highlightKeywords - highlight Specific word in Sentence / String
/**
* @author Gideon
*
* @see "https://medium.com/androiddevelopers/spantastic-text-styling-with-spans-17b0c16b4568"
* @see "https://stackoverflow.com/a/65000483"
* @see SpanType -> enum type of Span
*
*
* @param highlightColor -> TIDAK WAJIB, keyword akan di rubah ke warna ini
* @param message - > WAJIB Di ISI, merupakan kalimat yang akan di tampilkan di text
* @param keywords -> WAJIB Di ISI, keyword (kata / karakter) yang akan di ubah
* @param proportion -> TIDAK WAJIB, mengganti Ukuran Keyword
* @param type -> TIDAK WAJIB, default mengubah keyword menjadi BOLD
*
*
*/
fun TextView.highlightKeywords(
highlightColor: Int = ContextCompat.getColor(
context,
androidx.appcompat.R.color.accent_material_light
),
message: String,
keywords: List<String>,
proportion: Float = 1f,
spanType: SpanType = SpanType.BOLD
){
val spannableString = SpannableString(message)
keywords.forEach { keyword ->
if (keyword.isNotBlank()) {
var startIndex = message.lowercase().indexOf(keyword.lowercase())
while (startIndex >= 0) {
spannableString.setSpan(
when (spanType) {
SpanType.FOREGROUND -> ForegroundColorSpan(highlightColor)
SpanType.RELATIVE -> RelativeSizeSpan(proportion)
SpanType.QUOTE -> QuoteSpan(highlightColor)
SpanType.BOLD -> StyleSpan(Typeface.BOLD)
},
startIndex,
startIndex + keyword.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
startIndex = message.lowercase().indexOf(keyword.lowercase(), startIndex + keyword.length)
}
}
}
text = spannableString
}
/**
*
*
* Example Usage
* binding?.apply {
with(tvTitle) {
highlightKeywords(
message = "Hello World, and Hello to all my Hello Friends.",
keywords = listOf("l"),
highlightColor = Color.RED,
spanType = SpanType.FOREGROUND
)
}
}
*
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment