概述
showHighText 是一个 Kotlin 函数,用于在 TextView 中突出显示关键字。
工作原理:
- 首先,函数检查
contentText和keyword是否为空。如果是,则不做任何操作并返回。 - 然后,函数创建一个
SpannableStringBuilder对象。该对象允许我们将不同的样式(例如突出显示)应用于文本的部分。 - 接下来,函数将
keyword参数转换为小写并存储在lowercaseKeywords列表中。这确保了后续的大小写不敏感匹配。(也可以自己更改一下,加一个参数动态设置) - 然后,函数使用管道 ("|") 符号将
lowercaseKeywords连接起来创建一个正则表达式。这允许我们匹配contentText中的任何关键字。 - 最后,函数使用
Matcher对象在contentText中查找匹配的关键字。对于每个匹配的关键字,函数会将ForegroundColorSpan应用于相应的文本范围,以突出显示该关键字。
总的来说,showHighText 函数提供了一种方便的方法来突出显示 TextView 中的多个关键字,可以指定不同的颜色。
效果


代码
kotlin
fun TextView.showHighText(
contentText: String,
vararg keyword: String,
colors: List<Int> = listOf(MaterialColors.getColor(this, android.R.attr.colorPrimary))
) {
if (contentText.isNullOrEmpty() || keyword.isNullOrEmpty()) return
val stringBuilder = SpannableStringBuilder(contentText)
val lowercaseKeywords = keyword.map { it.lowercase(Locale.getDefault()) }
val regex = lowercaseKeywords.joinToString("|")
val matcher = Pattern.compile(regex).matcher(contentText.lowercase(Locale.getDefault()))
while (matcher.find()) {
val start = matcher.start()
val end = matcher.end()
val color = colors[start % colors.size]
stringBuilder.setSpan(
ForegroundColorSpan(color),
start,
end,
Spanned.SPAN_INCLUSIVE_INCLUSIVE
)
}
this.text = stringBuilder
}
代码解析
函数签名
kotlin
fun TextView.showHighText( contentText: String, vararg keyword: String, colors: List<Int> = listOf(MaterialColors.getColor(this, android.R.attr.colorPrimary)) )
-
该函数有三个参数:
contentText: 要显示在 TextView 中的主文本。keyword: 要突出显示在contentText中的关键字,可以传入多个。colors: (可选) 用于突出显示关键字的颜色列表。如果未提供,将使用主题中的默认颜色。
函数体
-
空值检查 : 函数首先检查
contentText或keyword是否为空或空。如果是,则不做任何操作并返回。 -
SpannableStringBuilder: 创建一个名为stringBuilder的SpannableStringBuilder对象。此对象允许我们将不同的样式(例如突出显示)应用于文本的部分。 -
小写关键字: 将
keyword参数转换为小写并存储在lowercaseKeywords列表中。这确保了后续的大小写不敏感匹配。 -
正则表达式: 使用管道 ("|") 符号将
lowercaseKeywords连接起来创建一个正则表达式。这允许我们匹配contentText中的任何关键字。 -
Matcher: 使用编译后的正则表达式和contentText的 lowercase 版本创建一个Matcher对象。 -
突出显示循环: 函数进入一个循环,直到
matcher无法找到任何更多关键字匹配。在循环中:- 获取匹配关键字的
start和end位置。 - 使用
start位置与colors列表大小的模来确定突出显示的颜色。这确保每个关键字都获得不同的颜色(如果提供了足够的颜色)。 - 创建具有所选颜色的
ForegroundColorSpan对象。 - 将
ForegroundColorSpan应用于匹配关键字范围(start到end) 在stringBuilder对象中。
- 获取匹配关键字的
-
设置文本: 最后,将
text属性设置为stringBuilder对象。这将显示原始文本以及突出显示的关键字。
使用
kotlin
binding.titleTextView.showHighText(title,keyword)
binding.contentTextView.showHighText(content,keyword,keyword2,keyword3,
colors = listOf<Int>(
Color.parseColor("#5F8670"),
Color.parseColor("#FF9800")
)
)
注意
假设 colors 列表至少有与关键字数量相同的元素。如果没有,则默认使用Colors中的第1个颜色