“一行代码解决 Android 关键字高亮、多种颜色“ Kotlin 扩展函数版

概述

showHighText 是一个 Kotlin 函数,用于在 TextView 中突出显示关键字。

工作原理:

  1. 首先,函数检查 contentTextkeyword 是否为空。如果是,则不做任何操作并返回。
  2. 然后,函数创建一个 SpannableStringBuilder 对象。该对象允许我们将不同的样式(例如突出显示)应用于文本的部分。
  3. 接下来,函数将 keyword 参数转换为小写并存储在 lowercaseKeywords 列表中。这确保了后续的大小写不敏感匹配。(也可以自己更改一下,加一个参数动态设置)
  4. 然后,函数使用管道 ("|") 符号将 lowercaseKeywords 连接起来创建一个正则表达式。这允许我们匹配 contentText 中的任何关键字。
  5. 最后,函数使用 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: (可选) 用于突出显示关键字的颜色列表。如果未提供,将使用主题中的默认颜色。

函数体

  1. 空值检查 : 函数首先检查 contentTextkeyword 是否为空或空。如果是,则不做任何操作并返回。

  2. SpannableStringBuilder: 创建一个名为 stringBuilderSpannableStringBuilder 对象。此对象允许我们将不同的样式(例如突出显示)应用于文本的部分。

  3. 小写关键字: 将 keyword 参数转换为小写并存储在 lowercaseKeywords 列表中。这确保了后续的大小写不敏感匹配。

  4. 正则表达式: 使用管道 ("|") 符号将 lowercaseKeywords 连接起来创建一个正则表达式。这允许我们匹配 contentText 中的任何关键字。

  5. Matcher: 使用编译后的正则表达式和 contentText 的 lowercase 版本创建一个 Matcher 对象。

  6. 突出显示循环: 函数进入一个循环,直到 matcher 无法找到任何更多关键字匹配。在循环中:

    • 获取匹配关键字的 startend 位置。
    • 使用 start 位置与 colors 列表大小的模来确定突出显示的颜色。这确保每个关键字都获得不同的颜色(如果提供了足够的颜色)。
    • 创建具有所选颜色的 ForegroundColorSpan 对象。
    • ForegroundColorSpan 应用于匹配关键字范围(startend) 在 stringBuilder 对象中。
  7. 设置文本: 最后,将 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个颜色

参考文章

Android设置文本关键字高亮效果

相关推荐
聆风吟º36 分钟前
【Spring Boot 报错已解决】别让端口配置卡壳!Spring Boot “Binding to target failed” 报错解决思路
android·java·spring boot
非专业程序员Ping8 小时前
HarfBuzz概览
android·ios·swift·font
Jeled9 小时前
「高级 Android 架构师成长路线」的第 1 阶段 —— 强化体系与架构思维(Clean Architecture 实战)
android·kotlin·android studio·1024程序员节
明道源码11 小时前
Kotlin 控制流、函数、Lambda、高阶函数
android·开发语言·kotlin
橙子1991101611 小时前
在 Kotlin 中,ViewModel 的获取
开发语言·vue.js·kotlin
hweiyu0011 小时前
Gradle 构建脚本迁移:从 Groovy DSL 到 Kotlin DSL,语法与技巧对比
开发语言·kotlin·gradle
消失的旧时光-194311 小时前
搞懂 Kotlin 的 List、Set、Map、HashMap、LinkedHashMap,以及 asSequence() 的底层原理与实战场景。
kotlin·数据处理·1024程序员节
明道源码11 小时前
Kotlin 面向对象编程、主构造函数、次构造函数、伴生对象、数据类、继承
kotlin·1024程序员节
消失的旧时光-194313 小时前
Kotlin × Gson:为什么遍历 JsonObject 要用 entrySet()
android·kotlin·数据处理·1024程序员节
G果14 小时前
安卓APP页面之间传参(Android studio 开发)
android·java·android studio