Home > Back-end >  Multiple colors in TextField not working for all words in Kotlin
Multiple colors in TextField not working for all words in Kotlin

Time:05-25

I'm making an IDE for Kotlin, I want to be able to color the keywords with blue color but it doesn't filter the second or the third ... etc from the beginning as follows:

enter image description here

I tried different regex patterns but didn't get what I desired.

Here is my function :

fun buildAnnotatedStringWithColors(code: String): AnnotatedString {
    val pattern = "[ \\t]"
    val words: List<String> = code.split(pattern.toRegex())
    val builder = AnnotatedString.Builder()
    for (word in words) {
        when (word) {
            in keywordList -> {
                builder.withStyle(
                    style = SpanStyle(
                        color = funKeyWords,
                        fontWeight = FontWeight.Bold
                    )
                ) {
                    append("$word ")
                }
            }
            else -> {
                builder.withStyle(
                    style = SpanStyle(
                        color = PrimaryColor,
                        fontWeight = FontWeight.Bold
                    )
                ) {
                    append("$word ")
                }
            }
        }
    }
    return builder.toAnnotatedString()
}

I want to be able to have white spaces, and new lines, and be colored at the same time so [\\s] doesn't work for me.

CodePudding user response:

I think something like this might work

fun buildAnnotatedStringWithColors(code: String): AnnotatedString {
    val pattern = "(?<=[\\s])"
    val words: List<String> = code.split(pattern.toRegex())
    val builder = AnnotatedString.Builder()
    for (word in words) {
        when (word.trim()) {
            in keywordList -> {
                builder.withStyle(
                    style = SpanStyle(
                        color = funKeyWords,
                        fontWeight = FontWeight.Bold
                    )
                ) {
                    append(word)
                }
            }
            else -> {
                builder.withStyle(
                    style = SpanStyle(
                        color = PrimaryColor,
                        fontWeight = FontWeight.Bold
                    )
                ) {
                    append(word)
                }
            }
        }
    }
    return builder.toAnnotatedString()
}
  • Related