You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android实现多单词高亮功能:给定示例代码与效果示例

Android实现多单词高亮功能方案

嘿,刚好做过类似的需求!在Android里要实现指定多单词的高亮,最直接的方式就是用SpannableString结合字符匹配来给目标单词添加样式,比如修改文字颜色或者背景色。下面给你完整的实现方案:

核心实现思路

我们要遍历每个需要高亮的单词,在全文本中找到所有匹配的位置,然后给这些位置的字符添加ForegroundColorSpan(前景色高亮)或者BackgroundColorSpan(背景色高亮),最后把处理好的SpannableString设置到TextView里就行。

完整代码示例

这里写一个通用的工具方法,你可以直接放到项目里用:

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;

public class HighlightUtils {
    /**
     * 多单词高亮方法
     * @param fullText 完整文本
     * @param highlightedWords 需要高亮的单词数组
     * @param highlightColor 高亮颜色(比如Color.RED)
     * @return 处理后的SpannableString
     */
    public static SpannableString highlightMultipleWords(String fullText, String[] highlightedWords, int highlightColor) {
        SpannableString spannableString = new SpannableString(fullText);
        
        for (String word : highlightedWords) {
            if (word == null || word.isEmpty()) {
                continue;
            }
            int wordLength = word.length();
            int startIndex = 0;
            
            // 循环查找所有匹配的单词位置
            while ((startIndex = fullText.indexOf(word, startIndex)) != -1) {
                int endIndex = startIndex + wordLength;
                // 设置高亮样式
                spannableString.setSpan(new ForegroundColorSpan(highlightColor),
                        startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                startIndex = endIndex; // 移动指针,避免重复匹配同一个位置
            }
        }
        
        return spannableString;
    }
}

怎么使用这个方法

比如就用你给的示例数据,在Activity或者Fragment里这么调用:

String highlightedWords[] = {"We", "country"};
String fullText = "We love our country a lot.";
// 比如用红色高亮
SpannableString highlightedText = HighlightUtils.highlightMultipleWords(fullText, highlightedWords, getResources().getColor(R.color.red));
// 设置到TextView
yourTextView.setText(highlightedText);

小扩展:忽略大小写的高亮

如果需要忽略大小写匹配(比如文本里是"we"也能高亮),可以修改查找逻辑,把全文本和单词都转成小写来匹配:

// 修改while循环里的查找逻辑
String lowerFullText = fullText.toLowerCase();
String lowerWord = word.toLowerCase();
while ((startIndex = lowerFullText.indexOf(lowerWord, startIndex)) != -1) {
    int endIndex = startIndex + word.length();
    spannableString.setSpan(new ForegroundColorSpan(highlightColor),
            startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    startIndex = endIndex;
}

其他样式可选

除了前景色,你还可以用这些Span实现不同的高亮效果:

  • BackgroundColorSpan:给单词加背景色
  • StyleSpan(Typeface.BOLD):把单词设置为粗体
  • UnderlineSpan:给单词加下划线

内容的提问来源于stack exchange,提问作者Ahamadullah Saikat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:58:26