Compose 小功能记录---Text关键字高亮

613 阅读1分钟

效果

search-input.gif

代码

Text(
    text = buildAnnotatedString {
        append(`allText`) //要显示的内容
        addStyle(
            SpanStyle(color_cm),
            keyword.start, //关键字在原始显示内容中开始的下标
            keyword.end //关键字在原始显示内容中结束的下标
        )
    }
)

Text 要使用 buildAnnotatedString 来拼接字符串并且要加上一个关键字的Style. 关键点是 Style 中的关键字在要显示内容中的下标怎么获取.

private fun highLightIndex(allText: String, word: String): ArrayList<Int> {
    val indexList = arrayListOf<Int>()
    val p = Pattern.compile(word)
    val m = p.matcher(allText)
    while (m.find()) {
        val start = m.start()
        val end = m.end()
        if (indexList.isEmpty()) {
            indexList.add(start)
            indexList.add(end)
        }
    }
    return indexList
}

这里通过使用 **Pattern** **Matcher** 来实现过滤相同字符串.

主要看下 Matcher


//在创建Matcher的时候,需要先创建Pattern
Pattern pattern =Pattern.complie(String regex)
Matcher matcher=pattern.matcher( String imput);

Boolean boolean = matcher.matcher();
//参数说明: boolean-只有整个matcher中的input字符串与pattern的匹配规则完全匹配的时候返回true,否则返回falseBoolean boolean = matcher.find();
//参数说明: boolean-当matcher中的input字符串具有与pattern的规则匹配的时候返回true,否则返回false//booleantrue的时候,我们可以调用
//matcher.start();返回匹配到的子字符串在字符串中的索引位置
//matcher.end();返回匹配到的子字符串的最后一个字符在字符串中的索引位置
//matcher.group();返回匹配到的子字符串
//注意:当多次调用find()的时候,会在字符串中寻找下一个能够匹配这则表达式的子字符串;

根据正则的过滤获取下标, 根据下标给Text添加颜色, 效果就实现了.