I have a TextView with a random background color (could be any color really). I also have a text on this Textview that need to be readable. I assume the best solution is to highlight the said text in white and set the text color to black.
My question is: Is it possible to highlight the text inside a texview from the XML?
I have the following in my layout:
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/colorButton4"
android:layout_gravity="right|bottom"
android:background="@drawable/layout_border"
android:layout_marginRight="30dp"
android:layout_marginBottom ="30dp"
android:clickable="true"
android:onClick="onClick"
android:gravity="center"
android:textColorHighlight="@color/bgWhite"
android:textColor="@color/Black"
android:text="5431354" />
But it deosn't highlight the text.
I've wrote a Kotlin method that will highlight all the keywords in all occurrences in the String
and will return SpannableString
.
fun main() {
textView.text = highlightKeywords(
highlightColor = ContextCompat.getColor(context, R.color.colorAccent),
message = "Hello World, and Hello to all my Hello Friends.",
keywords = listOf("Hello")
)
}
fun highlightKeywords(
highlightColor: Int,
message: String,
keywords: List<String>,
): SpannableString {
val spannableString = SpannableString(message)
keywords.forEach { keyword ->
if (!keyword.isBlank()) {
var startIndex = message.indexOf(keyword)
while (startIndex >= 0) {
spannableString.setSpan(
ForegroundColorSpan(highlightColor),
startIndex,
startIndex + keyword.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
startIndex = message.indexOf(keyword, startIndex + keyword.length)
}
}
}
return spannableString
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With