TextField 中的多种颜色不适用于 Kotlin 中的所有单词
Multiple colors in TextField not working for all words in Kotlin
我正在为 Kotlin 制作一个 IDE,我希望能够用蓝色为关键字着色,但它不会从头开始过滤第二个或第三个......等等,如下所示:
我尝试了不同的正则表达式模式,但没有得到我想要的。
这是我的函数:
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()
}
我希望能够有空格和新行,并同时着色,所以 [\\s] 对我不起作用。
我认为这样的方法可能有效
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()
}
我正在为 Kotlin 制作一个 IDE,我希望能够用蓝色为关键字着色,但它不会从头开始过滤第二个或第三个......等等,如下所示:
我尝试了不同的正则表达式模式,但没有得到我想要的。
这是我的函数:
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()
}
我希望能够有空格和新行,并同时着色,所以 [\\s] 对我不起作用。
我认为这样的方法可能有效
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()
}