Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

highlight text inside a textview

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.

like image 511
Slamit Avatar asked Jul 21 '16 16:07

Slamit


Video Answer


1 Answers

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
}
like image 107
Morgan Koh Avatar answered Sep 17 '22 13:09

Morgan Koh